以 HTML 格式下载 Zip 文件

时间:2021-07-15 08:23:16

标签: java google-chrome download zip microsoft-edge

我正在使用 Java Web 应用程序使用响应输出流创建一个 zip 文件,并设置响应标头。

当 Chrome/Edge 开始下载文件时,它们会将其视为 html 文件而不是 zip。

将下载的 .html 重命名为 .zip 然后给出正确的文件,所以我正确地创建了 zip。

如果我将 Edge 设置为提示下载,而不是自动下载文件,那么我可以在下载时将其视为 zip 文件。

IE11 以 zip 格式正确下载。

我的代码做错了什么?

ServletOutputStream servletOutputStream = response.getOutputStream();
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(servletOutputStream));
zos.putNextEntry(new ZipEntry(file.getName()));
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis= new BufferedInputStream(fis);

// Write the contents of the file
int data = 0;
while ((data = bis.read()) != -1) 
{
   zos.write(data);
}
bis.close();
fis.close();
zos.flush();
zos.closeEntry();
zos.close();
servletOutputStream.close();

response.setContentType("Content-type: text/zip");
response.setHeader("Content-Disposition", "attachment; filename=fileName.zip");

1 个答案:

答案 0 :(得分:0)

在做任何其他事情之前先尝试设置标题