spring mvc adds JSON message converter for multipart/form-data

In my Spring MVC server, I want to receive a multipart/form-data request containing a file (image) and some JSON metadata. I can build well-formed multipart requests where the JSON part has Content-Type=application/json.
The form of the Spring service is as follows:

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

The file is uploaded correctly, but I'm having trouble 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

If I don't use multipart request the JSON conversion works fine with 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:

mvc:annotation-driven
mvc:message-converters

</mvc:message-converters>
</mvc:annotation-driven>
If I use String as type of myClass instead of MyClass, but I want to use Spring MVC Argument transformations are supported, all of which work very well.

If you use the @RequestPart annotation instead of @RequestParam it will actually pass the parameter through the message converter. So if you change your controller method to the following it should work as you stated:

@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

Guess you like

Origin blog.csdn.net/qq_41604890/article/details/128235436