我正在尝试创建一个Rest服务,以使用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是异步写入的(在config类中启用了异步)。
如何使用此服务并完全以我使用的存储库中的文件形式编写文件? (如果可能的话,可以使用Postman进行测试)
我是否正确构建服务?
答案 0 :(得分:0)
我修改了一点代码,在我的documentId中是要下载文件的名称。我已经测试过,它工作正常。检查下面的代码。
@GetMapping(path = "/downloadFile")
public ResponseEntity<StreamingResponseBody> downloadFile(
@RequestParam(value = "documentId") String documentId,
HttpServletRequest request,
HttpServletResponse response)
throws InterruptedException, IOException {
String dirPath = "E:/sure-delete/"; //Directory having the files
InputStream inputStream = new FileInputStream(new File(dirPath + documentId));
final StreamingResponseBody out =
outputStream -> {
int nRead;
byte[] data = new byte[1024];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
System.out.println("Writing some bytes of file...");
outputStream.write(data, 0, nRead);
}
};
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));
}