我正在创建在正文响应中发送文件的 spring boot 应用程序,对此我使用以下代码:
FileSystemResource pdfFile = new FileSystemResource(outputFile);
return ResponseEntity
.ok()
.contentLength(pdfFile.contentLength())
.contentType(MediaType.parseMediaType("application/pdf"))
.body(new ByteArrayResource(IOUtils.toByteArray(pdfFile.getInputStream())));
我想知道除了使用 FileSystemResource 之外是否还有其他发送文件的方法?
拜托,如果有任何建议,请不要犹豫。
谢谢!
最佳答案
这是我通常做法的简化版本,但它做的事情几乎是一样的:
@RequestMapping(method = RequestMethod.GET, value = "/{id}")
public ResponseEntity<byte[]> getPdf(@PathVariable Long id) throws IOException {
final String filePath = pdfFilePathFinder.find(id);
final byte[] pdfBytes = Files.readAllBytes(Paths.get(filePath));
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
headers.setContentDispositionFormData("attachment", null);
headers.setCacheControl("no-cache");
return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
}
关于java - 在 Spring Boot 中发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55630863/