孙卫琴《精通Spring》的学习笔记:用WebFlux框架上传和下载文件

小编:大闷头 更新时间:2022-08-24

本文选自孙卫琴的《精通Spring:Java Web开发技术详解》清华大学出版社出版

技术支持网址为:​ ​ www.javathinker.net/spring.jsp​​

​本书对应的直播和录播课:​​ ​ www.javathinker.net/zhibo.jsp​​

孙卫琴的QQ学习答疑群:915851077


孙卫琴《精通Spring》的学习笔记:用WebFlux框架上传和下载文件


本文介绍在WebFlux框架中采用异步非阻塞的方式上传或下载文件。

以下例程1的FileController类的upload()方法和download()方法分别用于上传和下载文件。

​例程1 FileController.java

@RestController public class FileController { @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) publicMono upload( @RequestPart("file") FilePart filePart) throws IOException { System.out.println(filePart.filename()); FilenewFile = new File("C:\\helloapp", filePart.filename()); newFile.createNewFile(); PathdestFile = Paths.get("C:\\helloapp", filePart.filename()); //第一种上传方式 filePart.transferTo(destFile.toFile()); //第二种上传方式 /* AsynchronousFileChannel channel = AsynchronousFileChannel.open(destFile, StandardOpenOption.WRITE); DataBufferUtils.write(filePart.content(), channel, 0) .doOnComplete(() -> { System.out.println("finish"); }) .subscribe(); */ System.out.println(destFile); returnMono.just(filePart.filename()); } @GetMapping("/download") publicMono download ( ServerHttpResponse response) throws IOException { Stringfilename = "static\\book.png"; ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response; response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename); response.getHeaders().setContentType(MediaType.IMAGE_PNG); Resourceresource = new ClassPathResource(filename); File file= resource.getFile(); returnzeroCopyResponse.writeWith(file, 0, file.length()); } }

1.上传文件

//upload()方法

public Monoupload(@RequestPart("file") FilePart filePart)

以上的upload()方法的filePart参数为org.springframework.http.codec.multipart.FilePart类型,FilePart类的transferTo()方法采用异步非阻塞的方式上传文件。这里所谓异步非阻塞,是指transferTo()方法仅仅向底层Spring框架提交了一个上传文件的任务,而执行transferTo()方法的当前线程不会在方法中阻塞,而是立即退出来,执行后续代码,向客户端返回响应数据。所以当客户端收到响应结果时,有可能服务器端还在后台继续执行上传文件的任务。

FilePart接口的transferTo()方法的返回类型为Mono

reactor.core.publisher.MonotransferTo(File dest)

本文介绍的上传文件有两种方式,第一种方式是调用filePart参数的transferTo()方法:

filePart.transferTo(destFile.toFile());​

上传文件的第二种方式是通过异步文件通道java.nio.channels.AsynchronousFileChannel来上传文件:​

AsynchronousFileChannel channel = AsynchronousFileChannel.open( destFile, StandardOpenOption.WRITE); DataBufferUtils.write(filePart.content(), channel,0) .doOnComplete(() -> { System.out.println("finish"); }) .subscribe();


2.下载文件

FileController类的download()方法的response参数表示响应结果,它属于ServerHttpResponse类型。ServerHttpResponse接口来自于WebFlux API,能够按照异步非阻塞的方式输出响应数据,这意味着客户端在下载文件过程中不会被阻塞,还可以同时执行其他的操作。

3.运行程序

用Intellij IDEA运行本范例程序,再通过浏览器访问:

http://localhost:8080/fileio.html

会出现如图1所示的网页,在网页上执行上传文件的操作,FileController类会把文件上传到服务器端的helloapp根目录下。在网页上执行下载文件的操作,FileController类会把服务器端的helloapp\target\classes\static\book.png文件下载到客户端。

孙卫琴《精通Spring》的学习笔记:用WebFlux框架上传和下载文件孙卫琴《精通Spring》的学习笔记:用WebFlux框架上传和下载文件

图1 fileio.html网页