Spring WebFlux - 内容类型 'application/xml' 不支持 bodyType=org.springframework.web.multipart.MultipartFile

Spring WebFlux - Content type 'application/xml' not supported for bodyType=org.springframework.web.multipart.MultipartFile

我正在使用 spring-webflux 并想上传文件....仅使用 spring-web 一切正常,但当涉及到 webflux 时,我不知道哪里出了问题。

注意区别...我正在使用:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

所以假设我们有下面的 @RestController ,因为 Spring Web 它像魅力一样工作:

@PostMapping(value = "/uploadFile")
public Response uploadFile(@RequestParam("file") MultipartFile file) {

}

现在尝试对 Spring-webflux 进行相同操作会产生以下错误:

{
    "timestamp": "2019-04-11T13:31:01.705+0000",
    "path": "/upload",
    "status": 400,
    "error": "Bad Request",
    "message": "Required MultipartFile parameter 'file' is not present"
}

我从 random Whosebug 问题中发现我必须使用 @RequestPart 而不是 @RequestParam 但现在我收到以下错误并且我不知道为什么发生这种情况?

错误如下:

{
    "timestamp": "2019-04-11T12:27:59.687+0000",
    "path": "/uploadFile",
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'application/xml' not supported for bodyType=org.springframework.web.multipart.MultipartFile"
}

即使 .txt 文件也会产生相同的错误:

{
    "timestamp": "2019-04-11T12:27:59.687+0000",
    "path": "/uploadFile",
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'application/xml' not supported for bodyType=org.springframework.web.multipart.MultipartFile"
}

下面是 Postman Configuration,它非常简单,我只是用 post 请求调用并只修改了正文,如图所示。

顺便说一下,我也在 application.properties 上添加了所需的属性 :)

## MULTIPART (MultipartProperties)
# Enable multipart uploads
spring.servlet.multipart.enabled=true
# Threshold after which files are written to disk.
spring.servlet.multipart.file-size-threshold=2KB
# Max file size.
spring.servlet.multipart.max-file-size=200MB
# Max Request Size
spring.servlet.multipart.max-request-size=215MB

作为documentation说:

The DefaultServerWebExchange uses the configured HttpMessageReader<MultiValueMap<String, Part>> to parse multipart/form-data content into a MultiValueMap.

To parse multipart data in streaming fashion, you can use the Flux returned from an HttpMessageReader instead.

用几句话,你需要做这样的事情:

    @RequestMapping(path = "/uploadFile", method = RequestMethod.POST, 
        consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Flux<String> uploadFile(@RequestBody Flux<Part> parts) {
    //...
    }

看看这个example