Solve why wenflux fails to respond when using transferTo to upload files
I just learned webflux and am wondering how to upload files?
Then I searched on Baidu and saw a lot of answers. In the end, it was like this
(I just want to say that they are all the same, they look exactly the same, and they are copied too seriously).
Then method 1 works, but I want to use method 2, but nothing works. :
//NOTE 方法1
AsynchronousFileChannel channel =
AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE);
DataBufferUtils.write(filePart.content(), channel, 0)
.doOnComplete(() -> {
System.out.println("finish");
})
.subscribe();
//NOTE 方法二
//filePart.transferTo(tempFile.toFile());
Solution: (It’s funny to say, because it was the first day I learned this thing, and I forgot about the problem of no execution without subscribing, so I just added subscription at the end)
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Mono<String> requestBodyFlux(@RequestPart("file") FilePart filePart) throws IOException {
//这一种就比较简单
// FileOutputStream outputStream=new FileOutputStream("src/main/resources/".concat(filePart.filename()));
// DataBufferUtils.write(filePart.content(),outputStream).subscribe();
//这个方法最简单
File file=new File("src/main/resources/".concat(filePart.filename()));
filePart.transferTo(file).subscribe();
return Mono.just(filePart.filename());
}
Can you advise those people to copy it and try it themselves? What a waste of time...
File upload using webflux's webclient
You can check out this URL. It has a good introduction to webclient file uploading (https://www.modb.pro/db/143719).
I will choose a smaller code and post it:
WebClient webClient = WebClient.create("http://127.0.0.1:8080");
String fileName = webClient
.post()
.uri("/upload")
.body(BodyInserters.fromMultipartData("file", new ByteArrayResource(Files.readAllBytes(Path.of("D:\\下载\\123.jpeg"))){
@Override
public String getFilename() {
return "456.png";
}
}))
.retrieve().bodyToMono(String.class).block();
System.out.println(fileName);