我一直在开发一个java web应用程序,我想添加一个下载功能。 我想下载位于" C:\ apache-tomcat-6.0.36 \ webapps \ xml \ XML.zip"中的zip文件。 我已将文件转换为InputStream,但我仍然对如何从InputStream获取输入流数据感到困惑?
当我单击下载按钮时,它返回zip文件的0(零)字节
这是处理下载zipfile的控制器:
@RequestMapping("download")
public String Download(HttpServletResponse response) {
ZipInputStream zis = null;
try {
InputStream is = new FileInputStream("C:\\apache-tomcat-6.0.36\\webapps\\xml\\XML.zip");
zis = new ZipInputStream(is);
response.setHeader("Content-Disposition", "inline;filename=\"" + "XML.zip" + "\"");
OutputStream out = response.getOutputStream();
response.setContentType("application/zip");
IOUtils.copy(zis.getInputStream, out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
此行导致零字节zip文件:
IOUtils.copy(**zis.getInputStream**, out);
答案 0 :(得分:2)
假设您的代码编译:
如果您已经提取了一个zip文件,则无需再次通过ZipInputStream传递它。
像这样的事情 http://www.avajava.com/tutorials/lessons/how-do-i-serve-up-a-pdf-from-a-servlet.html答案 1 :(得分:2)
如果您想要下载整个ZIP文件,则不必使用ZipInputStream
...即访问ZIP文件的内容 ... < / p>
而不是zis.getInputStream()
使用is.getInputStream()
,并删除与ZipInputStream
相关的代码:
@RequestMapping("download")
public String Download(HttpServletResponse response) {
//ZipInputStream zis = null; no need for this
try {
InputStream is = new FileInputStream("C:\\apache-tomcat-6.0.36\\webapps\\xml\\XML.zip");
//zis = new ZipInputStream(is); //no need for this
response.setHeader("Content-Disposition", "inline;filename=\"" + "XML.zip" + "\"");
OutputStream out = response.getOutputStream();
response.setContentType("application/zip");
IOUtils.copy(is, out); //no zis here, and "is" is already an InputStream instance
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
另外,我修改了.close()调用:它们几乎总是最适合finally
块,以确保正常关闭。 (或者使用try-with-resource块。)