在前面两篇基础文章的基础上,我们今天在学习第三章,WebFlux 的文件上传。为了演示效果,我这里前端借用了 Bootstrap 框架。而且是支持多语言,多文件,有进度条的上传,同时在上传之前还可以预览图片。前端的代码做法参考我的这篇文章:使用Bootstrap的fileinput插件实现多文件、多语言、可预览的上传功能。
在前面两篇的基础上,我们新建 webflux-file 工程。maven 的 pom.xml 和前面一样,启动类也一样。详情可以参考前面的两篇文章或者扫描文章末尾的二维码,关注“”微信公众号进行下载!
现在我们新建一个 FileRouter 类,或者 FileController 类也可以,后面我会说他们之间的区别。具体代码如下:
@RestController
public class FileRouter {
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Mono<String> requestBodyFlux(@RequestPart("file") FilePart filePart) throws IOException {
System.out.println(filePart.filename());
Path tempFile = Files.createTempFile("xttblog", filePart.filename());
//NOTE 方法一
AsynchronousFileChannel channel =
AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE);
DataBufferUtils.write(filePart.content(), channel, 0)
.doOnComplete(() -> {
System.out.println("finish");
})
.subscribe();
//NOTE 方法二
//filePart.transferTo(tempFile.toFile());
System.out.println(tempFile.toString());
return Mono.just(filePart.filename());
}
@GetMapping("/download")
public Mono<Void> downloadByWriteWith(ServerHttpResponse response) throws IOException {
ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response;
response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=xttblog.png");
response.getHeaders().setContentType(MediaType.IMAGE_PNG);
Resource resource = new ClassPathResource("xttblog.png");
File file = resource.getFile();
return zeroCopyResponse.writeWith(file, 0, file.length());
}
}
核心代码就这么多,上传下载全在这里。上传我们主要是使用了 FilePart 类和 @RequestPart("file") 注解。下载使用的是 webflux 提供的 ServerHttpResponse 类,直接将文件写入到输出流。
fileinput.js 实现文件上传的运行效果


文件上传后,控制台打印信息如下:
xttblog.png /var/folders/rc/z5hy_bp96_z43zy6mb7hqg4w0000gn/T/xttblog6929117607868758568xttblog.png finish
我这里是 mac 电脑,打印内容和 Linux 上一致。最后关于源码,扫描下方二维码,关注“”微信公众号,回复:“webflux”关键字即可免费下载!

: » Spring Boot WebFlux Bootstrap 文件上传
原创文章,作者:3628473679,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/251868.html