Reputation: 243
I need to parse a multipart request in a spring-mvc controller. Spring version is 4.1.6. Example of the request:
HEADER host: "localhost:8080"
HEADER accept: "*/*"
HEADER content-length: "539"
HEADER expect: "100-continue"
HEADER content-type: "multipart/form-data; boundary=------------------------2e2bf5fa2f7bbfbf"
BODY:
--------------------------2e2bf5fa2f7bbfbf
Content-Disposition: form-data; name="objectid"
160714.110239.GG
--------------------------2e2bf5fa2f7bbfbf--
Content-Disposition: form-data; name="geojson"
[a very long json string]
--------------------------2e2bf5fa2f7bbfbf
The exact formatting of the request is not under my control.
As long as I use the whole @RequestBody, my RequestMapping is resolved:
@RequestMapping(value = "/coordinates", method = RequestMethod.POST)
public @ResponseStatus(value = HttpStatus.OK)
void coordinates(final HttpServletRequest request,
final @RequestBody String body) {
final Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
final String element = headerNames.nextElement();
System.out.println("HEADER " + element + ": \"" + request.getHeader(element) + "\"" );
}
System.out.println("BODY:");
System.out.println(body);
}
But when I change the signature in order to get the parts directly, the client gets an error message, saying "Required String parameter 'objectid' is not present", and my mapping is not resolved anymore (tested with a breakpoint). This is the failing code:
@RequestMapping(value = "/coordinates", method = RequestMethod.POST)
public @ResponseStatus(value = HttpStatus.OK)
void coordinates(final HttpServletRequest request,
final @RequestParam("objectid") String objectid,
final @RequestParam("geojson") String geojson) {
final String remoteAddr = request.getRemoteAddr();
System.out.println("coordinates from " + remoteAddr
+ ":\nobjectid=" + objectid
+ "\ngeojson=" + geojson);
}
What am I doing wrong ?
Upvotes: 1
Views: 3183
Reputation: 243
Resolved.
There was one thing missing in my spring configuration:
<bean id="multipartResolver"
class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
<property name="maxUploadSize" value="100000"/>
</bean>
And with that resolver, the @RequestParam annotation (as in my second java source example) works. Yes, it's @RequestParam although the values are not part of the URL.
Upvotes: 1
Reputation: 31
Since you are submitting the data using POST method,multi-part content will go in the request body not as request parameters.
In second case, you annotated with request param object, spring will check for a parameter in the request url. If its not available spring will throw an error. Additionally you can make the request parameter as optional or you can give default value
Upvotes: 1