[英]Zip file getting downloaded without .zip extension in Chrome through Java
在我的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设置存在问题(只是一个猜测)。
有人可以帮忙吗?
提前致谢....
更改设置响应头和将文件推到输出流之间的顺序-毕竟,头需要先离开。
[编辑]
setHeader
调用时实际上会发送这些标头,这是一个很大的假设-我怀疑那些标头在调用response.getOutputStream
之后实际上不会发送-响应不太可能会缓冲整个有效负载以等待调用方指定这些标头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.