Webflux:将文件和 DTO 传递到单个请求中

Webflux: pass files and DTO into single request

我需要同时传递文件(通过 form-data)和 DTO。所以我尝试执行以下操作:

@PostMapping
public Mono<Void> method(@RequestPart("files") Flux<FilePart> files,
                         Dto dto) {
    return Mono.empty();
}

并通过每个 dto 字段的参数初始化 Dto

所以我得到以下错误:

org.springframework.core.codec.CodecException: Type definition error: [simple type, class org.springframework.http.codec.multipart.SynchronossPartHttpMessageReader$SynchronossFilePart]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.springframework.http.codec.multipart.SynchronossPartHttpMessageReader$SynchronossFilePart and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.LinkedHashMap["errors"]->java.util.Collections$UnmodifiableList[0]->org.springframework.validation.FieldError["rejectedValue"])
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.springframework.http.codec.multipart.SynchronossPartHttpMessageReader$SynchronossFilePart and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.LinkedHashMap["errors"]->java.util.Collections$UnmodifiableList[0]->org.springframework.validation.FieldError["rejectedValue"])

如果我完全删除 Dto 参数,图像会正确加载。

Dto 参数添加 @RequestBody 注释会产生以下错误:

Content type 'multipart/form-data;charset=UTF-8;boundary=rh4lsv9DycBf8hpV2snhKfRjSrj1GvHzVy' not supported for bodyType=com.example.Dto

通过将 Dto 传递为 @RequestParam("dto") String dto 并手动解析 JSON 来实现这一点,但这并不是一个真正完美的解决方案。

所以你需要所谓的 mixed multipart

@PostMapping("/test")
public Mono<Void> method(@RequestPart("dto") Dto dto, @RequestPart("files") Flux<FilePart> files) {

    return Mono.empty();
}

这适用于此 http 请求:

POST /test HTTP/1.1
Host: localhost:8080
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Cache-Control: no-cache
Postman-Token: 425629ec-335f-4d49-8df4-d6130af67889

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="files"; filename="Capture.PNG"
Content-Type: image/png


------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="dto"
Content-Type: application/json

{"test":"aaa"}

###

注:

   Content-Type: application/json

对于 dto 部分是 强制性的

看到这个答案:

Spring MVC Multipart Request with JSON