如何使用文件系统资源强制文件下载文件时设置“内容处置”和“文件名”?

2022-08-31 20:23:24

设置和使用Spring 3的最合适,最标准的方法是什么?Content-Disposition=attachmentfilename=xyz.zipFileSystemResource

操作如下所示:

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


答案 1

除了被接受的答案之外,Spring还具有专门用于此目的的类ContentDisposition。我相信它涉及文件名清理。

      ContentDisposition contentDisposition = ContentDisposition.builder("inline")
          .filename("Filename")
          .build();

      HttpHeaders headers = new HttpHeaders();
      headers.setContentDisposition(contentDisposition);

答案 2
@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);
}

推荐