使用FileSystemResource强制文件下载文件时,如何设置“ Content-Disposition”和“ Filename”?

发布于 2021-01-30 17:21:43

设置Content-Disposition=attachmentfilename=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存在时,标记为删除。

关注者
0
被浏览
74
1 个回答
  • 面试哥
    面试哥 2021-01-30
    为面试而生,有面试问题,就找面试哥。
    @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);
    }
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看