spring mvc为multipart/form-data添加JSON消息转换器

在我的Spring MVC服务器中,我想要接收包含文件(图像)和一些JSON元数据的multipart / form-data请求。 我可以在JSON部分具有Content-Type=application/json的情况下构建格式良好的多部分请求。
Spring服务的形式如下:

@RequestMapping(value = MY_URL, method=RequestMethod.POST, headers="Content-Type=multipart/form-data")
public void myMethod(@RequestParam("image") MultipartFile file, @RequestParam("json") MyClass myClass) {
    
    
...
}

该文件已正确上传,但我遇到了JSON部分的问题。我得到这个错误:

``
org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type ‘java.lang.String’ to required type ‘myPackage.MyClass’; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [myPackage.MyClass]: no matching editors or conversion strategy found

如果我不使用多部分请求JSON转换可以很好地使用Jackson 2,但是当使用多部分时,我会得到以前的错误。我想我必须配置多部分消息转换器来支持JSON作为消息的一部分,但我不知道如何。这是我的配置:

mvc:annotation-driven
mvc:message-converters

</mvc:message-converters>
</mvc:annotation-driven>
如果我使用String作为myClass的类型而不是MyClass,但是我希望使用Spring MVC支持进行参数转换,所有这些都可以很好地工作。

如果您使用@RequestPart注释而不是@RequestParam,它实际上将通过消息转换器传递参数。 因此,如果您将控制器方法更改为以下内容,它应该如您所述:

@RequestMapping(value = MY_URL, method=RequestMethod.POST, headers="Content-Type=multipart/form-data")
public void myMethod(@RequestParam("image") MultipartFile file, @RequestPart("json") MyClass myClass) {
    
    
...
}

您可以在Spring参考指南中阅读更多相关信息:http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/mvc.html#mvc-multipart-forms-non-browsers

猜你喜欢

转载自blog.csdn.net/qq_41604890/article/details/128235436
今日推荐