spring springboot webflux 文件上传下载

webflux 的文件上传下载功能

文件上传

RestController架构

webflux直接提供了RequestPart注解,让我们拿到上传的文件数据

@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());
    return Mono.just(filePart.filename());
}

说明:使用RequestPart来接收,得到的是FilePart
FilePart的content是Flux,可以使用DataBufferUtils写到文件或者直接使用transferTo写入到文件

Route Handler架构

很多时候,我们使用 router 如下指定接口访问入口

@Bean
    RouterFunction<ServerResponse> myRouter(IndustryChainHandler icHandler) {
        return nest(
                path("/v2.0/mynetwork"),
                route(POST("/upload"), myHandler::upload));
}

此时不方便直接拿到RequestPart 数据,但是其实数据都还是在ServerRequest里面,变换一下就可以了。

public Mono<ServerResponse> upload(ServerRequest request) {
        return ok().contentType(APPLICATION_JSON_UTF8).body(
                request.body(BodyExtractors.toMultipartData()).map(parts -> {
                    Map<String, Part> map = parts.toSingleValueMap();
                    // ‘files’ 为客户端上传文件key
                    FilePart filePart = (FilePart) map.get("files");
                    try {
                        // 第一个参数是上传文件的前缀,可以随便起名字
                        Path tempFile = Files.createTempFile("upload_file", filePart.filename());
                        File dest = tempFile.toFile();
                        filePart.transferTo(dest);
                        return filePart.filename();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return "";
                }).map(filename -> {
                    if (!StringUtils.isEmpty(filename)) {
                        return "OK";
                    } else {
                        return "error";
                    }
                }), String.class
        );

文件下载

方法1:

@GetMapping("/download")
public Mono<Void> downloadByWriteWith(ServerHttpResponse response) throws IOException {
	ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response;
	response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=myimage.png");
	response.getHeaders().setContentType(MediaType.IMAGE_PNG);
	Resource resource = new ClassPathResource("parallel.png");
	File file = resource.getFile();
	return zeroCopyResponse.writeWith(file, 0, file.length());
}

方法2:

@GetMapping("/download")
public Mono<ServerResponse> downloadByWriteWith(ServerRequest request) throws IOException {
	Resource resource = new ClassPathResource("myimage.png");
	return ok().header("Content-Disposition", "attachment; filename=myimage.png")
	.body(BodyInserters.fromResource(resource)).switchIfEmpty(Mono.empty());
}

说明:两种方法都是将数据写入ServerHttpResponse,方法2可以在配合path.route使用

Spring Boot提供了一些方便的类和方法来实现文件上传下载。下面分别介绍如何实现文件上传文件下载。 ## 文件上传 ### 1. 引入依赖 在 `pom.xml` 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 添加文件上传依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> ``` ### 2. 配置文件上传路径 在 `application.properties` 文件中添加以下配置: ```properties # 上传文件保存目录 spring.servlet.multipart.location=上传文件保存目录 # 文件上传限制 spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB ``` ### 3. 编写文件上传接口 在控制器中编写文件上传接口: ```java @RestController public class FileController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { // 获取上传文件名 String fileName = file.getOriginalFilename(); // 保存上传文件 file.transferTo(new File("上传文件保存目录/" + fileName)); return "上传成功!"; } } ``` ### 4. 测试文件上传 启动应用后,使用 `curl` 命令或者浏览器访问 `http://localhost:8080/upload` 接口进行文件上传,例如: ```bash curl -X POST -F file=@/path/to/file http://localhost:8080/upload ``` ## 文件下载 ### 1. 编写文件下载接口 在控制器中编写文件下载接口: ```java @RestController public class FileController { @GetMapping("/download") public ResponseEntity<Resource> downloadFile(@RequestParam("fileName") String fileName) throws IOException { // 获取文件流 InputStreamResource resource = new InputStreamResource(new FileInputStream("文件保存目录/" + fileName)); // 设置响应头 HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=" + fileName); // 返回文件流 return ResponseEntity.ok() .headers(headers) .contentLength(resource.contentLength()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(resource); } } ``` ### 2. 测试文件下载 启动应用后,使用 `curl` 命令或者浏览器访问 `http://localhost:8080/download?fileName=文件名` 接口进行文件下载,例如: ```bash curl -OJL http://localhost:8080/download?fileName=example.txt ```
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值