spring webflux系列之文件流下载文件(不用本地创建文件直接文件流下载)
继承上一篇spring webflux系列之上传文件(多)到七牛云篇
网上基本上全部教程都是创建本地文件 才去下载 又要删除本地文件
这里使用到流下载文件 也就是inputStream 和 outputStream 都行
还是直接贴代码(简易版本)
@GetMapping(value = "/downloadFile")
public Mono<Void> downloadTest(ServerHttpResponse response) {
File file = new File("C:\\Users\\zjian\\Desktop\\cache\\test.xlsx");
//这里为了模拟流 而去读取本地文件
FileInputStream in =null;
try {
in = new FileInputStream(file);
Flux<DataBuffer> dataBufferFlux = DataBufferUtils.readByteChannel(in::getChannel,new DefaultDataBufferFactory(),4096);
ZeroCopyHttpOutputMessage zeroCopyHttpOutputMessage = (ZeroCopyHttpOutputMessage)response;
HttpHeaders headers = zeroCopyHttpOutputMessage.getHeaders();
headers.set(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=test.xlsx");
//vnd.ms-excel 可以替换为 octet-stream
MediaType application = new MediaType("application", "vnd.ms-excel", Charset.forName("UTF-8"));
headers.setContentType(application);
return zeroCopyHttpOutputMessage.writeWith(dataBufferFlux);
} catch (Exception e) {
e.printStackTrace();
}
return Mono.empty();
}
简易版本 自己稍加修改就能使用
这里简单的展示inputstream的 想用outputstream直接改成outputstream就行
in::getChannel 是创建流通道(管道)
DefaultDataBufferFactory是默认工厂 你也可以自己自定义处理工厂
4096后面是读取size
后续我会继续更新spring webflux 系列
并整合成项目开源 github开源地址