如何启用 Spring Reactive Web MVC 来处理 Multipart-file?

How to enable Spring Reactive Web MVC to handle Multipart-file?

我正在尝试在 spring boot 2.0 应用程序中使用新的反应式 web-mvc 实现。我正在尝试定义一种使用多部分文件但无法使其正常工作的方法:( - 我总是收到 415 错误。

一方面,我有一个包含以下请求映射的控制器:

@RequestMapping(method = RequestMethod.POST, path = "/myPath/{param}/{param2}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
public Mono<Void> postFile(
        @RequestBody MultipartFile data,
        @PathVariable("param") String param,
        @PathVariable("param2") String param2,
        @RequestHeader(name = HEADER_DATE, required = false)   @DateTimeFormat(pattern = DATE_FORMAT) Instant instant
){
    return fileService.handleData(Mono.just(data), param, param2, instant);
}

另一方面,我不得不在基本依赖项之上添加一个服务器,因为 netty 似乎不处理多部分文件。我因此添加了 spring-boot-starter-tomcat 依赖项,它使 MultipartAutoConfiguration 能够匹配并满足应用程序自动配置。

使用 curl 调用发布内容时: curl 'Meta-Date: 20170101104532' --form "file=@file.bin" http://localhost:8082/myPath/foo/bar 当调试日志被激活时 (logging.level.org.springframework.web=DEBUG) 我得到了这个异常: org.springframework.web.server.UnsupportedMediaTypeStatusException: Request failure [status: 415, reason: "Content type 'multipart/form-data;boundary=------------------------58fa43b8f1a26de4' not supported"]

此错误是由 RequestBodyArgumentResolver 引发的,它具有以下受支持的媒体类型:[*/*, text/xml, application/*+json;charset=UTF-8, application/xml, text/plain;charset=UTF-8, application/x-www-form-urlencoded, application/json;charset=UTF-8] 由 9 DecoderHttpMessageReader.

提供

发帖前我也看了:

我的理解是 Spring web 5.0 使用新的请求解码器系统,因为我在 spring 4 spring 启动应用程序中找不到这些 类,并且还没有任何 DecoderHttpMessageReader 处理多部分文件 我错过了什么 ?还是我应该等待一个实施?

好吧,这似乎暂时没有实现,因为它目前存在针对此功能的拉取请求:Add reactive multipart request support #1201

应该早点检查一下...

[编辑]:问题已解决并合并到 Spring master 分支。应该不再是问题。

@PutMapping(value="/{..}",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Mono<Void> save(@RequestPart("file") FilePart multipartFormData,@RequestParam("fileName") String fileName,@PathVariable("..") String ..) throws IOException {        
        List<ByteBuffer> bytesList = new LinkedList<>();

        multipartFormData.content().
          subscribe(item->bytesList.add(item.asByteBuffer()));

        int totalBytes = bytesList.stream().mapToInt(item->item.capacity()).sum();

        ByteBuffer buffer =  ByteBuffer.allocate(totalBytes);
        bytesList.stream().forEach(byteBuff->buffer.put(byteBuff));
        baseImageHandler.saveImage(buffer, fileName, baseItemId);
        return Mono.empty();
    }

请注意,这是一个开发版本,但这是我设法做到的。