`

服务端推送multipart/x-mixed-replace

    博客分类:
  • java
阅读更多

往网页分批推送数据:boundary=END,总头-->分头-->Body

@GetMapping("/test")
    public void testjpg(HttpServletResponse response) throws IOException{
        response.setContentType("multipart/x-mixed-replace;boundary=END");

        // Set the content type based on the file type you need to download
        String contentType = "Content-type: image/jpeg";

        // List of files to be downloaded
        List<File> files = new ArrayList();
        files.add(new File("C:\\Users\\Administrator\\Desktop\\qq\\51.jpg"));
        files.add(new File("C:\\Users\\Administrator\\Desktop\\qq\\52.jpg"));
        files.add(new File("C:\\Users\\Administrator\\Desktop\\qq\\53.jpg"));

        ServletOutputStream out = response.getOutputStream();

        // Print the boundary string
        out.println();
        out.println("--END");

        for(int i =0;i<500;i++) {
            for (File file : files) {

                // Get the file
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(file);

                } catch (FileNotFoundException fnfe) {
                    // If the file does not exists, continue with the next file
                    System.out.println("Could not find file " + file.getAbsolutePath());
                    continue;
                }

                BufferedInputStream fif = new BufferedInputStream(fis);

                // Print the content type
                out.println(contentType);
                out.println("Content-Disposition: attachment; filename=" + file.getName());
                out.println();

                System.out.println("Sending file " + file.getName());

                // Write the contents of the file
                int data = 0;
                while ((data = fif.read()) != -1) {
                    out.write(data);
                }
                fif.close();


                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // Print the boundary string
                out.println();
                out.println("--END");
                out.flush();
                System.out.println("Finished sending file " + file.getName());
            }
        }
        // Print the ending boundary string
        out.println("--END--");
        out.flush();
        out.close();

    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics