spring - 使用 Webflux 下载文件并在浏览器中查看的更好方法
问题描述
我正在学习 WebFlux。我正在从如下所示的休息端点下载文件:
@RequestMapping(value = { "/downloadAlfFile/{id}" }, method = RequestMethod.GET)
private static ResponseEntity<byte[]> getFileContent(@PathVariable String id) throws IOException {
String uri = "http://localhost:8080/api/1/downloadcontent/" + id
+ "/getcontent";
String fileName = getFileNameMethod(id); // filename here
WebClient client = WebClient.builder().baseUrl(uri).build(); // the WebClient
Flux<DataBuffer> dataBufferFlux = client.get().headers(headers -> headers.setBasicAuth("admin", "admin"))
.accept(MediaType.APPLICATION_OCTET_STREAM).retrieve().bodyToFlux(DataBuffer.class); // dataBuffer
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachement; filename=\"" + fileName + "\"")
.body(getInputStreamFromFluxDataBuffer(dataBufferFlux).readAllBytes());
}
public static InputStream getInputStreamFromFluxDataBuffer(Flux<DataBuffer> data) throws IOException {
PipedOutputStream osPipe = new PipedOutputStream();
PipedInputStream isPipe = new PipedInputStream(osPipe);
DataBufferUtils.write(data, osPipe).subscribeOn(Schedulers.boundedElastic()).doOnComplete(() -> {
try {
osPipe.close();
} catch (IOException ignored) {
}
}).subscribe(DataBufferUtils.releaseConsumer());
return isPipe;
}
- 问题1:有没有更好的方法来实现同样的目标?我正在寻求帮助,因为上面看起来像是补丁工作而不是干净的代码。
- 问题 2:如何在浏览器中打开 pdf/images 而不是使用 webflux 下载它们?我试过
in-line
而不是attachment
但没有帮助。我应该怎么办?
解决方案
推荐阅读
- sql - 选择...进入...从... Excel 表格进入 Access 生成表格查询
- git - 我分支了错误的分支,如何将更改移动到正确的分支?
- python - 同时控制步进电机和相机
- bash - Bash 脚本自动回答命令
- javascript - 如何在 Hightcharts / Highstock 中获取隐藏系列的数据?
- arrays - 如何从 findOne Mongoose 获取对象内部的数组
- batch-file - 在睡眠事件上运行脚本
- r - nchar(desc) 中的错误:无效的多字节字符串,使用 map() 和 rvest 时网页抓取时的元素 1
- python - 如何删除数据类属性
- java - ListView 中的 Wicket 表单组件值更改会影响所有元素