为多部分/表单数据添加JSON消息转换器 [英] Add JSON message converter for multipart/form-data
问题描述
在Spring MVC服务器中,我想接收包含文件(图像)和一些JSON元数据的multipart/form-data请求.
我可以在JSON部分包含Content-Type=application/json
的地方构建格式正确的多部分请求.
Spring服务的形式为:
In my Spring MVC server I want to receive a multipart/form-data request containing both a file (an image) and some JSON metadata.
I can build a well-formed multipart request where the JSON section has Content-Type=application/json
.
The Spring service is in the form:
@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部分出现问题.我收到此错误:
The file is correctly uploaded, but I'm having problems with the JSON part. I get this error:
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
如果我不使用多部分请求,则使用Jackson 2可以很好地进行JSON转换,但是当使用多部分时,我会得到先前的错误.我认为我必须配置多部分消息转换器以支持JSON作为消息的一部分,但我不知道如何.这是我的配置:
If I don't use multipart request JSON conversion works well using Jackson 2, but when using multipart I get the previous error. I think I have to configure the multipart message converter to support JSON as part of the message, but I don't know how. Here is my configuration:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
如果我将String用作myClass的类型而不是MyClass,则所有方法都可以正常工作,但是我想使用Spring MVC支持进行参数转换.
All works well if I use String as type of myClass instead of MyClass, but I want to use the Spring MVC support for parameter conversion.
推荐答案
如果使用@RequestPart
注释而不是@RequestParam
,它将实际上通过消息转换器传递参数.
因此,如果将控制器方法更改为以下方法,则它应如您所描述的那样起作用:
If you use the @RequestPart
annotation instead of @RequestParam
, it will actually pass the parameters through the message converters.
So, if you change your controller method to the following, it should work as you describe:
@RequestMapping(value = MY_URL, method=RequestMethod.POST, headers="Content-Type=multipart/form-data")
public void myMethod(@RequestParam("image") MultipartFile file, @RequestPart("json") MyClass myClass) {
...
}
You can read more about it in the Spring reference guide: http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/mvc.html#mvc-multipart-forms-non-browsers
这篇关于为多部分/表单数据添加JSON消息转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!