java 将 ZipOutputStream 返回到浏览器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5516922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning ZipOutputStream to browser
提问by stevebot
I have an ZipOutputStream that I want to return to the browser. The experience I would like is that the user clicks an anchor tag, and then a file download prompt is displayed for the ZipOutputStream that I have.
我有一个 ZipOutputStream 想要返回到浏览器。我想要的体验是,用户单击一个锚点标签,然后为我拥有的 ZipOutputStream 显示文件下载提示。
How do you get the ZipOutputStream back to the browser?
您如何将 ZipOutputStream 返回到浏览器?
回答by Jberg
Just had to do this exact same thing yesterday.
昨天只需要做完全相同的事情。
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(baos);
.... populate ZipOutputStream
String filename = "out.zip";
// the response variable is just a standard HttpServletResponse
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
response.setContentType("application/zip");
try{
response.getOutputStream().write(baos.toByteArray());
response.flushBuffer();
}
catch (IOException e){
e.printStackTrace();
}
finally{
baos.close();
}
Note I'm using a ByteArrayOutputStream wrapper and toByteArray but you could probably just write any other type of Outputstream directly to the response with a standard InputStream.read() OutputStream.write() loop.
注意我使用的是 ByteArrayOutputStream 包装器和 toByteArray,但您可能只是使用标准 InputStream.read() OutputStream.write() 循环将任何其他类型的 Outputstream 直接写入响应。
Off hand I'm actually not sure which is faster if any, but I suspect my use of ByteArrayOutputStream here might not be the most memory conscious approach:
暂时我实际上不确定哪个更快,但我怀疑我在这里使用 ByteArrayOutputStream 可能不是最注重内存的方法: