【发布时间】:2017-08-31 04:00:09
【问题描述】:
我不明白为什么这这么难而且每个人都有自己的实现......
所以在我的服务器中,我生成了一个.zip 文件,我希望用户能够在单击时下载该文件。
所以我设置了服务器成功接收的请求,现在,我正在努力将字节数组写入输出。
这是我的响应代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Downloading clusters.zip");
/* Generate the directory on the server, then zip it. */
clustersToFiles();
zipClusters();
/* Now the zip is saved on zipFullPath */
System.out.println("Done generating the .zip");
String parent_dir = System.getProperty("catalina.base");
String filename = "clusters.zip";
String zipFullPath = parent_dir + "/" + filename;
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
OutputStream out = response.getOutputStream();
FileInputStream fis = new FileInputStream(zipFullPath);
int bytes;
while ((bytes = fis.read()) != -1) {
System.out.println(bytes);
out.write(bytes);
}
fis.close();
response.flushBuffer();
System.out.println(".zip file downloaded at client successfully");
}
【问题讨论】:
-
@pandaadb 如果你认为
frameworks可能会在这里帮助我,无论如何...... -
实际上,我认为您的问题不是 servlet 部分,而是复制部分。如果您愿意,我可以发布球衣示例以供下载。至于框架,可以通过例如将任何文件复制到输出流中来实现。 google commons:
Files.copy(new File("path/to/zip/file"), output);另外,如果这适用于普通文件,您确定您生成的 zip 文件不只是空的吗?您尝试复制的文件不应该有所不同