I need to send FilePart received in RestController to API using WebClient, how can I do this?
Found an example, which saves image to disk.
private static String UPLOAD_ROOT = "C:\\pics\\";
public Mono<Void> checkInTest(@RequestPart("photo") Flux<FilePart> photoParts,
@RequestPart("data") CheckInParams params, Principal principal) {
return saveFileToDisk(photoParts);
}
private Mono<Void> saveFileToDisk(Flux<FilePart> parts) {
return parts
.log("createImage-files")
.flatMap(file -> {
Mono<Void> copyFile = Mono.just(Paths.get(UPLOAD_ROOT, file.filename()).toFile())
.log("createImage-picktarget")
.map(destFile -> {
try {
destFile.createNewFile();
return destFile;
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.log("createImage-newfile")
.flatMap(file::transferTo)
.log("createImage-copy");
return Mono.when(copyFile)
.log("createImage-when");
})
.log("createImage-flatMap")
.then()
.log("createImage-done");
}
Then read it again and send to anoter server
.map(destFile -> {
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
try {
map.set("multipartFile", new ByteArrayResource(FileUtils.readFileToByteArray(destFile)));
} catch (IOException ignored) {
}
map.set("fileName", "test.txt");
WebClient client = WebClient.builder().baseUrl("http://localhost:8080").build();
return client.post()
.uri("/upload")
.contentType(MediaType.MULTIPART_FORM_DATA)
.syncBody(map)
.exchange(); //todo handle errors???
}).then()
Is there way to avoid saving file?
I will mention solution by @Abhinaba Chakraborty
provided in https://stackoverflow.com/a/62745370/4551411
Probably something like this:
@PostMapping(value = "/images/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Mono<ResponseEntity<Void>> uploadImages(@RequestPart("files") Flux<FilePart> fileParts) {
return fileParts
.flatMap(filePart -> {
return webClient.post()
.uri("/someOtherService")
.body(BodyInserters.fromPublisher(filePart.content(), DataBuffer.class))
.exchange()
.flatMap(clientResponse -> {
//some logging
return Mono.empty();
});
})
.collectList()
.flatMap(response -> Mono.just(ResponseEntity.accepted().build()));
}
This accepts MULTIPART FORM DATA where you can attach multiple image files and upload them to another service.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With