sequence
This article mainly describes the file upload and download of spring webflux.
maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
File Upload
@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());
}
Use RequestPart to receive, the content of FilePart FilePart is Flux<DataBuffer>, you can use DataBufferUtils to write to the file or directly use transferTo to write to the file
document dowload
@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());
}
Here data is written to ServerHttpResponse
summary
Using webflux, there is no HttpServletRequest and HttpServletReponse based on the servlet container before, instead org.springframework.http.server.reactive.ServerHttpRequest and org.springframework.http.server.reactive.ServerHttpResponse.