使用Spring 3 Content-Disposition=attachment
设置filename=xyz.zip
和FileSystemResource
的最合适,最标准的方法是什么?
Action 看起来像:
@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
方法。附言此处使用的文件是一个临时文件,当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);
}