使用FileSystemResource强制文件下载文件时如何设置'Content-Disposition'和'Filename'? [英] How to set 'Content-Disposition' and 'Filename' when using FileSystemResource to force a file download file?
问题描述
设置 Content-Disposition = attachment
和 filename = xyz.zip $ c的最合适,最标准的方法是什么? $ c>使用Spring 3
FileSystemResource
?
What is the most appropriate, and standard, way to set the Content-Disposition=attachment
and filename=xyz.zip
using 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文件,但浏览器总是下载文件,但是我想明确提到该文件为附件,并提供与文件实际名称无关的文件名。
Although the file is a zip file so the browser always downloads the file, but I would like to explicitly mention the file as attachment, and also provide a filename that has nothing to do with the files actual name.
这个问题可能有解决方法,但我想知道正确的Spring和 FileSystemResource
方法来实现这一目标。
There might be workarounds for this problem, but I would like to know the proper Spring and FileSystemResource
way to achieve this goal.
PS这里使用的文件是一个临时文件,在JVM存在时标记为删除。
P.S. The file that is being used here is a temporary file, marked for deletion when the JVM exists.
推荐答案
@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);
}
这篇关于使用FileSystemResource强制文件下载文件时如何设置'Content-Disposition'和'Filename'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!