在我的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浏览器设置存在问题,我需要考虑(只是猜测)。
有人可以为此提供帮助吗?
提前致谢....
答案 0 :(得分:1)
更改设置响应标头和将文件推送到输出流之间的顺序 - 毕竟,标头需要先离开。
[被修改]
setHeader
调用时发送这些标头,这是一个很大的假设 - 我怀疑在调用response.getOutputStream
之后实际上不会发送这些标头 - 它响应不太可能缓冲整个有效负载,等待调用者指定这些头。