如何在不获取 "No suitable writer found exception" 的情况下将异步数据写入远程端点?

How to write async data to remote endpoint without getting "No suitable writer found exception"?

我有以下控制器方法:

@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE, path = "/upload")
public Mono<SomeResponse> saveEnhanced(@RequestPart("file") Mono<FilePart> file) {
    return documentService.save(file);
}

调用服务方法,我尝试使用 WebClient 将一些数据放入另一个应用程序:

public Mono<SomeResponse> save(Mono<FilePart> file) {
    MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();
    bodyBuilder.asyncPart("file", file, FilePart.class);
    bodyBuilder.part("identifiers", "some static content");
    return WebClient.create("some-url").put()
            .uri("/remote-path")
            .syncBody(bodyBuilder.build())
            .retrieve()
            .bodyToMono(SomeResponse.class);

}

但我收到错误:

org.springframework.core.codec.CodecException: No suitable writer found for part: file

我尝试了 MultipartBodyBuilder 的所有变体(部分、asyncpart,有或没有 headers),但我无法让它工作。

我是不是用错了,我错过了什么?

此致, 亚历克斯

在 Spring 框架 Github 问题部分的一位贡献者的回复后,我找到了解决方案。 为此:

The asyncPart method is expecting actual content, i.e. file.content(). I'll update it to unwrap the part content automatically.

bodyBuilder.asyncPart("file", file.content(), DataBuffer.class)
    .headers(h -> {
        h.setContentDispositionFormData("file", file.name());
        h.setContentType(file.headers().getContentType());
    });

如果两个 headers 都没有设置,那么请求将在远程端失败,表示找不到表单部分。

祝所有需要这个的人好运!