Bk *_*ago 4 java spring-boot reactive spring-webflux
我有以下端点代码可提供PDF文件。
@RequestMapping
ResponseEntity<byte[]> getPDF() {
File file = ...;
byte[] contents = null;
try {
try (FileInputStream fis = new FileInputStream(file)) {
contents = new byte[(int) file.length()];
fis.read(contents);
}
} catch(Exception e) {
// error handling
}
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData(file.getName(), file.getName());
headeres.setCacheControl("must-revalidate, post-check=0, pre-check=0");
return new ResponseEntity<>(contents, headers, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
我如何才能将上面转换为反应类型Flux/Mono
和DataBuffer
。
我有支票,DataBufferUtils
但似乎没有提供我需要的东西。我也没有找到任何例子。
最简单的方法是使用Resource
。
@GetMapping(path = "/pdf", produces = "application/pdf")
ResponseEntity<Resource> getPDF() {
Resource pdfFile = ...;
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData(file.getName(), file.getName());
return ResponseEntity
.ok().cacheControl(CacheControl.noCache())
.headers(headers).body(resource);
}
Run Code Online (Sandbox Code Playgroud)
请注意,这里DataBufferUtils
有一些将InputStream
a 转换为a的有用方法Flux<DataBuffer>
,例如DataBufferUtils#read()
。但是处理a Resource
仍然更好。
归档时间: |
|
查看次数: |
2797 次 |
最近记录: |