Can i attach multiple attachments in one HttpServl

2019-02-16 01:21发布

For example, i would like to download one zip file and one csv file in one response. Is there any way other than compressing these two files in one zip file.

3条回答
ら.Afraid
2楼-- · 2019-02-16 01:27

Although ServletResponse is not meant to do this, we could programmatically tweak it to send multiple files, which all client browsers except IE seems to handle properly. A sample code snippet is given below.

response.setContentType("multipart/x-mixed-replace;boundary=END");
ServletOutputStream out = response.getOutputStream();
out.println("--END");
for(File f:files){
      FileInputStream fis = new FileInputStream(file);
      BufferedInputStream fif = new BufferedInputStream(fis);
      int data = 0;
      out.println("--END");
      while ((data = fif.read()) != -1) {
        out.write(data);
      }
      fif.close();
      out.println("--END");
      out.flush();
}
out.flush();
out.println("--END--");
out.close();

This will not work in IE browsers. N.B - Try Catch blocks not included

查看更多
地球回转人心会变
3楼-- · 2019-02-16 01:46

No you can not do that. The reason is that whenever you want to sent any data in request you use steam available in request and retrive this data using request.getRequestParameter("streamParamName").getInputStream(), also please make a note if you have already consumed this stream once you will not be able to get it again.

The example mentioned above is a tweak that google also uses in sending multipart email with multiple attachments. To achieve that they define boundaries for each attachment and client have to take care of these boundaries while retrieving this information and rendering it.

查看更多
干净又极端
4楼-- · 2019-02-16 01:48

Code developed by Jason Hunter to handle servlet request and response having multiple parts has been the defacto since years. You can find it at servlets.com

查看更多
登录 后发表回答