Spring Webflux Upload Large Image File and Send The File with WebClient in Streaming Way

Viewed 2889

I am using spring webflux functional style. I want to create a endpoint which accepts large image files and send this files to another service with webClient in streaming way.

All file processing should be in streaming way because I don't want to my app crush because of outofmemory.

Is there anyway to do this ?

1 Answers

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.

Related