Spring Webflux 文件上传和下载
最编程
2024-05-01 20:52:44
...
序
本文主要讲述一下spring webflux的文件上传和下载。
maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
文件上传
@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("test", 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());
}
使用RequestPart来接收,得到的是FilePart
FilePart的content是Flux<DataBuffer>,可以使用DataBufferUtils写到文件
或者直接使用transferTo写入到文件
文件下载
@GetMapping("/download")
public Mono<Void> downloadByWriteWith(ServerHttpResponse response) throws IOException {
ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response;
response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=parallel.png");
response.getHeaders().setContentType(MediaType.IMAGE_PNG);
Resource resource = new ClassPathResource("parallel.png");
File file = resource.getFile();
return zeroCopyResponse.writeWith(file, 0, file.length());
}
这里将数据写入ServerHttpResponse
小结
使用webflux就没有之前基于servlet容器的HttpServletRequest及HttpServletReponse了,取而代之的是org.springframework.http.server.reactive.ServerHttpRequest以及org.springframework.http.server.reactive.ServerHttpResponse。
doc
- MultipartIntegrationTests
上一篇: SWFUpload 用户指南
推荐阅读
-
Spring Webflux 文件上传和下载
-
在 Spring Boot 中实现文件上传和下载
-
RESTful 文件上传和下载
-
将文件上传到 Spring boot 项目的 Python 请求模块
-
实现文件上传和读取的 Blob 对象
-
@RequestPart 同时上传文件和 json 的解决方案
-
Java 继承了 Minio 以实现文件上传、文件下载、文件删除等功能。
-
使用 winzip 生成的扩展名为 -ZIP 的压缩文件通常使用".zip "扩展名,其 MIME 格式为 application/zip。(推荐学习:phpstorm) 目前,ZIP 格式属于几种主流压缩格式之一,其竞争对手包括 RAR 格式和开源的 7z 格式。 从性能对比来看,RAR 和 7z 格式比 ZIP 格式压缩率更高,而 7-Zip 由于提供免费压缩工具而逐渐在更多领域得到应用。 微软从 Windows ME 操作系统开始就内置了对 zip 格式的支持,即使用户没有在电脑上安装解压软件,也可以打开和创建 zip 格式的压缩文件,OS X 和流行的 Linux 操作系统也提供了类似的 zip 格式支持。 因此,如果要在网络上传播和分发文件,zip 格式往往是最常见的选择。
-
使用 Android DownloadManager 下载和安装 apk 文件
-
上传和下载鳄梨酱