Spring ResponseEntity 是否将资源中的完整数据加载到内存中?
Does Spring ResponseEntity load the full data from a Resource into Memory?
我正在编写一个需要 return 来自另一个网络服务器的 PDF 文件的方法:
@RequestMapping(value = "download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String document) throws Exception {
String file = "http://blabla.com?document=" + document;
HttpHeaders headers = new HttpHeaders();
headers.add("content-disposition", "attachment; filename=" + document);
headers.setContentType(MediaType.APPLICATION_PDF);
UrlResource u = new UrlResource(new URL(file));
return ResponseEntity.ok().headers(headers).body(u);
}
这似乎有效。然而,PDF 可能会变得很大,我不完全确定 ResponseEntity.body()
如何读取和写入文件。
此处是否正在将完整数据读入内存?如果是这样,我如何设法让它改为流式传输?
我知道如何使用 HttpServletResponse 和写入输出流来做到这一点,但我想知道 Spring 是否已经在此处解决了这个问题。
Spring 会为您解决这个问题。 Resource
响应通过从资源的输入流中读取并写入响应的输出流来流式传输到客户端。如果您想查看代码,this is done in ResourceHttpMessageConverter
.
我正在编写一个需要 return 来自另一个网络服务器的 PDF 文件的方法:
@RequestMapping(value = "download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String document) throws Exception {
String file = "http://blabla.com?document=" + document;
HttpHeaders headers = new HttpHeaders();
headers.add("content-disposition", "attachment; filename=" + document);
headers.setContentType(MediaType.APPLICATION_PDF);
UrlResource u = new UrlResource(new URL(file));
return ResponseEntity.ok().headers(headers).body(u);
}
这似乎有效。然而,PDF 可能会变得很大,我不完全确定 ResponseEntity.body()
如何读取和写入文件。
此处是否正在将完整数据读入内存?如果是这样,我如何设法让它改为流式传输?
我知道如何使用 HttpServletResponse 和写入输出流来做到这一点,但我想知道 Spring 是否已经在此处解决了这个问题。
Spring 会为您解决这个问题。 Resource
响应通过从资源的输入流中读取并写入响应的输出流来流式传输到客户端。如果您想查看代码,this is done in ResourceHttpMessageConverter
.