3

我正在返回一个 ResponseEntity 用于文件下载。

@RequestMapping("/download")
public ResponseEntity<byte[]> download(){
    byte[] fileContent = manager.getFile();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    headers.setPragma("cache");
    headers.setExpires(0);
    headers.setCacheControl("private");
    headers.setContentDispositionFormData("attachment", "sample.pdf");
    headers.setContentLength(fileContent.length);
    return new ResponseEntity<byte[]>(fileContent, headers, HttpStatus.OK); 
}

在 chrome 中,我遵循请求标头:

Cache-Control:no-store
Cache-Control:no-cache
Cache-Control:private
Content-Disposition:form-data; name="attachment"; filename="sample-pdf.pdf"
Content-Length:1469
Content-Type:application/pdf;charset=UTF-8
Date:Thu, 15 Aug 2013 08:10:25 GMT
Expires:Thu, 01 Jan 1970 00:00:00 GMT
Expires:Thu, 01 Jan 1970 00:00:00 GMT
Pragma:cache
Pragma:no-cache
Server:Apache-Coyote/1.1

如果我以旧方式使用 HttpServletResponse

public void download(HttpServletResponse response){
    byte[] fileContent = manager.getFile();
    response.reset();
    response.setContentType("application/pdf");
    response.setHeader("Pragma", "cache");
    response.setHeader("Expires", "0");
    response.setHeader("Cache-control", "private");
    response.setHeader("Content-Disposition", "attachment; filename=sample.pdf");
    FileCopyUtils.copy(fileContent, response.getOutputStream());
}

标题是我想要的

Cache-Control:private
Content-Disposition:form-data; name="attachment"; filename="sample-pdf.pdf"
Content-Length:1469
Content-Type:application/pdf;charset=UTF-8
Date:Thu, 15 Aug 2013 08:10:25 GMT
Expires:Thu, 01 Jan 1970 00:00:00 GMT
Pragma:cache
Server:Apache-Coyote/1.1

使用时有什么方法可以清理 http 标头值ResponseEntity吗?

4

1 回答 1

0

不使用

headers.setContentDispositionFormData("attachment", "sample.pdf");

或其他套装

仅使用添加方法,例如:

headers.add("Content-Disposition", "inline;filename=\"sample_"+System.currentTimeMillis()+".pdf\"");
于 2013-09-24T18:47:15.597 回答