Spring Web Reactive Framework 多部分文件问题

2024-03-29

我正在尝试使用 Spring 的响应式框架来实现图像上传,方法如下:

@RestController
@RequestMapping("/images")
public class ImageController {

    @Autowired
    private IImageService imageService;

    @PostMapping(value = "", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    Mono<ImageEntity> saveImage(@RequestBody Mono<FilePart> part) throws Exception{
         return part.flatMap(file -> imageService.saveImage(file));
    }
}

但我不断收到 415 错误消息,并显示以下错误消息:

Response status 415 with reason "Content type 'multipart/form-data;boundary=--0b227e57d1a5ca41' not supported\

不确定问题是什么,我按以下方式卷曲 API:

 curl -v -F "[email protected] /cdn-cgi/l/email-protection" -H "Content-Type: multipart/form-data" localhost:8080/images

我尝试了不同的标头和文件变体,但结果相同。这里有点不知所措,因为我过去曾经这样做过,而且事情似乎进展顺利。我从这篇文章中看到这个功能被合并了:

如何启用 Spring Reactive Web MVC 处理多部分文件? https://stackoverflow.com/questions/43066619/how-to-enable-spring-reactive-web-mvc-to-handle-multipart-file


经过深入研究,我在 Spring WebFlux 项目中找到了这个测试:

https://github.com/spring-projects/spring-framework/blob/master/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MultipartIntegrationTests.java https://github.com/spring-projects/spring-framework/blob/master/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MultipartIntegrationTests.java

所以我缺少的部分是@RequestPart代替@RequestBody在控制器定义中。

最终代码如下所示:

@RestController
@RequestMapping("/images")
public class ImageController {

    @Autowired
    private IImageService imageService;

    @PostMapping(value = "", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    Mono<ImageEntity> saveImage(@RequestPart("file") Mono<FilePart> part) throws Exception{
         return part.flatMap(file -> imageService.saveImage(file));
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Web Reactive Framework 多部分文件问题 的相关文章

随机推荐