ClosableHttpClient
,该方法应返回一些Stream。
public ResponseEntity<InputStreamResource> getFileAsStream(@PathVariable("uuid") String uuid) throws IOException, InterruptedException {
CloseableHttpResponse response = fileService.importFileByUuid(uuid);
try {
HttpEntity entity = response.getEntity();
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
responseHeaders.add(HttpHeaders.CONTENT_TYPE, entity.getContentType().getValue());
responseHeaders.add(HttpHeaders.CONTENT_DISPOSITION, response.getFirstHeader(HttpHeaders.CONTENT_DISPOSITION).getValue());
if (entity != null) {
InputStream inputStream = entity.getContent();
InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
return ResponseEntity.ok()
.headers(responseHeaders)
.body(inputStreamResource);
}
throw new IllegalStateException(String.format(
"Error during stream downloading, uuid = %s", uuid));
} finally {
response.close();
}
}
您始终可以创建从httpentity获得的输入流的副本,并使用副本创建响应率中返回的InputStreamResource。这样,可以在返回响应率之前安全地关闭从HTTPENTITY获得的原始输入流。
InputStream inputStream = entity.getContent();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
IOUtils.copy(inputStream, outputStream);
byte[] contentBytes = outputStream.toByteArray();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(contentBytes);
InputStreamResource inputStreamResource = new InputStreamResource(byteArrayInputStream);
或保存使用字节[]并使用它来返回
ByteArrayResource
而不是
InputStreamResource
使用Servlet API中的HTTP拖车标头的供应商来运行
.close()
侧效应。 filecontroller.java
@GetMapping(path = "/document")
public ResponseEntity<?> getSingleDocument(
@RequestParam(name = "docPath") String documentPath,
HttpServletResponse response
) {
return fileService.fetchPDF(documentPath, response);
}
FileService.java