java - 以 HTML 格式下载 Zip 文件
问题描述
我正在使用 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");
解决方案
在做任何其他事情之前先尝试设置标题
推荐阅读
- reporting-services - 即使详细信息为空,SSRS 2008 也会显示行
- c# - 如何将标题应用于文字处理文档中的所有段落?
- azure - 安装 MS Service Fabric SDK 3.2.162 时出现问题
- schema - Pentaho Schema Workbench 维度属性
- c# - UWP XAML 中的 YouTube 样式搜索结果
- python - ImportError:没有名为 miniconda 的模块
- ag-grid - 将列从像素宽度更改为百分比宽度以响应并在 ag-grid 中填充表格
- blogspot - 如何为 Blogspot 放置最佳元数据?
- json - 编码大型 numpy 数组并将其保存到 dynamodb
- groovy - Groovy:构造函数哈希冲突