Spring Webflux上传大图像文件并使用WebClient以流方式发送文件

mst*_*tzn 3 streaming file-upload spring-boot spring-webflux

我正在使用 spring webflux 功能风格。我想创建一个接受大图像文件的端点,并使用 webClient 以流方式将此文件发送到另一个服务。

所有文件处理都应该以流方式进行,因为我不想因为内存不足而导致我的应用程序崩溃。

有办法做到这一点吗?

Abh*_*rty 5

大概是这样的:

  @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()));
  }
Run Code Online (Sandbox Code Playgroud)

它接受多部分表单数据,您可以在其中附加多个图像文件并将它们上传到其他服务。