9

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) {
...
}

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

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>

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.

user1781028
  • 1,478
  • 4
  • 22
  • 45
  • I'm also facing similar issue http://stackoverflow.com/questions/18896648/json-post-spring-mvc-curl-400-bad-request but no solution yet – Pradeep Sep 20 '13 at 10:52

2 Answers2

8

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

Jasper Aarts
  • 91
  • 1
  • 6
1

i don't have any idea how do it this but i know @RequestParam("json") MyClass myClass u can change to @RequestParam("json") String myClass and build object class by JSON converted! It's not good but it's works

Denis
  • 69
  • 1
  • 5