首页 > 解决方案 > 如何将异步数据写入远程端点而不会出现“未找到合适的写入器异常”?

问题描述

我有以下控制器方法:

@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的所有变体(部分、异步部分、带或不带标题),但我无法让它工作。

我用错了吗,我错过了什么?

问候,亚历克斯

标签: spring-bootspring-webflux

解决方案


在从 Spring Framework Github 问题部分的一个贡献者那里得到回复后,我找到了解决方案。为此:

asyncPart 方法需要实际内容,即 file.content()。我将对其进行更新以自动解开零件内容。

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

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

祝任何需要这个的人好运!


推荐阅读