Spring-mvc – spring multipart file upload form validation

multipartform-dataspring-mvcvalidation

I'm new to spring, and i'm currently struggling with the many pieces required to get a multipart form submit/validation scenario with error beeing displayed in the view.

Here are the files i currently have :

resourceupload.jsp : a view that displays a form to upload the file.

<form:form method="post" action="resource/upload" enctype="mutlipart/form-data">
 <input name="name" type="text"/>
 <input name="file" type="file" />
 <input type="submit"/>
<form:errors path="file" cssClass="errors"/>
</form>

resourceuploadcontroller.java : the controller that handles the form submit, and (unsuccessfuly) tries to post file validation errors back to the view :

@RequestMapping(method = RequestMethod.POST)
public String handleFormUpload( @RequestParam("file") MultipartFile file , @RequestParam("name") String name,Object command, Errors validationErrors){
..perform some stuff with the file content, checking things in the database, etc...
.. calling validationErrors.reject("file","the error") everytime something goes wrong...

return "redirect:upload"; // redirect to the form, that should display the error messages

Now, obviously there's something wrong with this approach:

1/ I had to add a dummy "command" object before the validationErrors parameter, otherwise spring would throw me an error. That doesn't seem really right.

2/ After I added that parameter, the redirect doesn't pass the errors to the view. I tried using @SessionAttribute("file") at the start of the controller, without any luck.

If anyone could help… I've had a look at @ResponseBody annotation, but that doesn't seem to be made to be used with views..

Best Answer

Seems like I found the solution on my own.

First, the link that helped me a lot : http://www.ioncannon.net/programming/975/spring-3-file-upload-example/ and Spring 3 MVC - form:errors not showing the errors which showed a good trick to display all errors, using

<form:errors path="*"/>. 

Now, a list of all the things i changed to make that thing work :

1/ use "rejectValue" instead of "reject".

2/ return the view directly instead of a redirect.

3/ create a "UploadItem" model with a CommonsMultipartFile property

So, all in all, my controller method became

@RequestMapping(method = RequestMethod.POST)
public String handleFormUpload( @ModelAttribute("uploadItem") UploadItem uploadItem, BindingResult errors){
... use errors.rejectValue ... in case of errors (moving everything i could in a UploadItemValidator.validate function)
return "uploadform"

Hope that helped.