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

哈桑·贾米尔(Hassan Jamil):

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

哈桑·贾米尔(Hassan Jamil):
@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);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章