使用FileSystemResource强制文件下载文件时,如何设置“ Content-Disposition”和“ Filename”?
问题内容:
设置Content-Disposition=attachment
和filename=xyz.zip
使用Spring 3
的最合适,最标准的方法是FileSystemResource
什么?
动作看起来像:
@ResponseBody
@RequestMapping(value = "/action/{abcd}/{efgh}", method = RequestMethod.GET, produces = "application/zip")
@PreAuthorize("@authorizationService.authorizeMethod()")
public FileSystemResource doAction(@PathVariable String abcd, @PathVariable String efgh) {
File zipFile = service.getFile(abcd, efgh);
return new FileSystemResource(zipFile);
}
尽管该文件是zip文件,所以浏览器始终会下载该文件,但是我想明确提及该文件作为附件,并且还提供与该文件的实际名称无关的文件名。
可能有解决此问题的方法,但是我想知道适当的Spring和FileSystemResource
实现此目标的方法。
PS这里使用的文件是一个临时文件,当JVM存在时,标记为删除。
问题答案:
@RequestMapping(value = "/action/{abcd}/{efgh}", method = RequestMethod.GET)
@PreAuthorize("@authorizationService.authorizeMethod(#id)")
public HttpEntity<byte[]> doAction(@PathVariable ObjectType obj, @PathVariable Date date, HttpServletResponse response) throws IOException {
ZipFileType zipFile = service.getFile(obj1.getId(), date);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
response.setHeader("Content-Disposition", "attachment; filename=" + zipFile.getFileName());
return new HttpEntity<byte[]>(zipFile.getByteArray(), headers);
}