将ZipOutputStream返回到浏览器 [英] Returning ZipOutputStream to browser
问题描述
我有一个ZipOutputStream,我想返回浏览器。我想要的体验是用户单击一个锚标签,然后为我拥有的ZipOutputStream显示一个文件下载提示。
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传回浏览器?
How do you get the ZipOutputStream back to the browser?
推荐答案
昨天只需要做同样的事情。
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();
}
注意我正在使用ByteArrayOutputStream包装器和toByteArray,但您可能只需写入任何其他类型的OutputStream直接传递给具有标准InputStream.read()OutputStream.write()循环的响应。
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可能不是最有记忆力的方法:
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:
这篇关于将ZipOutputStream返回到浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!