【发布时间】:2019-10-12 07:12:29
【问题描述】:
我正在尝试使用 Springboot 创建一个休息服务来从存储库下载文件。
我正在尝试返回一个带有 StreamingResponseBody 的 ResponseEntity,以将我从存储库中获取的文件作为 InputStream 返回。
这是我当前的代码:
@GetMapping(path = "/downloadFile")
public ResponseEntity<StreamingResponseBody> downloadFile(@RequestParam(value = "documentId") String documentId,
HttpServletRequest request, HttpServletResponse response) throws InterruptedException, IOException {
InputStream is = downloadService.getDocument(documentId);
StreamingResponseBody out = outputStream -> {
outputStream.write(IOUtils.toByteArray(is));
};
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "text/csv");
headers.add("Content-Disposition", "attachment; filename=" + documentId);
headers.add("Pragma", "no-cache");
headers.add("Cache-Control", "no-cache");
return (new ResponseEntity<>(out, headers, HttpStatus.OK));
}
当我直接使用浏览器或邮递员使用此端点时,下载的文件为空。 我知道 OutputStream 是异步写入的(在配置类中启用了异步)。
如何使用此服务并完全写入文件,它来自我正在使用的存储库的方式? (如果可能,使用 Postman,仅用于测试目的)
我是否正确构建了服务?
【问题讨论】:
标签: java spring spring-boot