【发布时间】:2017-02-07 16:58:26
【问题描述】:
- 我正在尝试从服务器中的固定位置下载 zip 文件。
- 在我的 Rest 方法中,我只是从客户端(浏览器)传递文件名。 (请看下面的代码)。
在我的 Rest 方法中,我将 zip 文件发送到客户端。
文件在浏览器上下载没有任何问题。
我的问题是 zip 文件在没有 .zip 扩展名的情况下下载到浏览器上。
@RequestMapping(value = "/zip/{filePath}", method = RequestMethod.GET)
public @ResponseBody void downloadZip(@PathVariable("filePath") String filePath, HttpServletRequest request, HttpServletResponse response) throws IOException {
ServletContext context = request.getServletContext();
File downloadFile = new File(filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get output stream of the response
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[(int) downloadFile.length()];
int bytesRead = -1;
// write bytes read from the input stream into the output stream
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
response.setHeader("Content-Disposition",
String.format("attachment; filename=\"%s\"", downloadFile.getName()));
logger.error("Filename = " + downloadFile.getName());
inputStream.close();
outStream.close();
}
PS: 文件被下载到一些带有 ZIP 的机器上和一些没有 ZIP 的机器上。我只在 chrome 上测试过(根据客户要求)。 我认为,Chrome 设置存在问题,我需要查看(只是猜测)。
有人可以帮忙吗?
提前谢谢....
【问题讨论】:
-
更改设置响应标头和将文件推送到输出流之间的顺序 - 毕竟,标头需要先离开。
-
试过了,还是不行。无论如何,谢谢。
-
尝试mime-type为“application/zip, application/octet-stream”
-
嗨,阿德里安,感谢您的快速回复。 mime 类型已经是 application/zip。更新:更改响应标头序列解决了该问题。您能否在答案中发布相同的内容,以便我可以接受您的答案。非常感谢。
标签: java rest google-chrome servlets zip