本博客日IP超过2000,PV 3000 左右,急需赞助商。
极客时间所有课程通过我的二维码购买后返现24元微信红包,请加博主新的微信号:xttblog2,之前的微信号好友位已满,备注:返现
受密码保护的文章请关注“业余草”公众号,回复关键字“0”获得密码
所有面试题(java、前端、数据库、springboot等)一网打尽,请关注文末小程序
腾讯云】1核2G5M轻量应用服务器50元首年,高性价比,助您轻松上云
在前面两篇基础文章的基础上,我们今天在学习第三章,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”关键字即可免费下载!
最后,欢迎关注我的个人微信公众号:业余草(yyucao)!可加作者微信号:xttblog2。备注:“1”,添加博主微信拉你进微信群。备注错误不会同意好友申请。再次感谢您的关注!后续有精彩内容会第一时间发给您!原创文章投稿请发送至532009913@qq.com邮箱。商务合作也可添加作者微信进行联系!
本文原文出处:业余草: » Spring Boot WebFlux Bootstrap 文件上传