【发布时间】:2021-09-24 03:44:15
【问题描述】:
我正在使用 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");
【问题讨论】:
-
尝试先设置标题
-
您可以尝试将
Content-Type响应标头设置为值application/zip(或application/octet-stream,具体取决于目标浏览器)。 -
感谢@g00se 有效。彭旭东,那好像没什么区别,至少不是不做g00se的事。 G00se 如果你想写答案我会打勾
标签: java google-chrome download zip microsoft-edge