【java】一次http请求,下载多个文件,multipart/x-mixed-replace


public class DownloadMultipleFiles extends HttpServlet {

  private static final long serialVersionUID = 3305561818342965462L;

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // Set the response type and specify the boundary string
    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: text/rtf";

    // List of files to be downloaded
    List files = new ArrayList();
    files.add(new File("C:/first.txt"));
    files.add(new File("C:/second.txt"));
    files.add(new File("C:/third.txt"));

    ServletOutputStream out = response.getOutputStream();

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

    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();

      // 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();
  }

}

目前测试只支持火狐,后续研究为何chrome不支持

via:https://javadigest.wordpress.com/2012/02/13/downloading-multiple-files-using-multipart-response/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值