Friday, June 12, 2009

Spring MVC 2.5 uploading a file using CommonsMultipartResolver

3 Steps to upload a file in Spring MVC 2.5 using CommonsMultipartResolver

Step 1)
in your servlet.xml or applicationContext.xml paste the following code
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties overall request size(not file size) -->
<property name="maxUploadSize" value="100000"/>
</bean>


Step 2)
Code for Controller


@RequestMapping("/file-upload")
public ModelAndView uploadFile(
@RequestParam("file") CommonsMultipartFile file) {
//do whatever you want with the file object
return new ModelAndView();
}

step 3)
Html Code


<form action="file-upload.html" enctype="multipart/form-data" method="post">
<input name="file" type="file">
<input value="Upload" type="submit">
</form>

That's it. Questions or Comments?

Next post, redirect the user back to the entry form if the upload file size exceeded the maxUploadsize parameter. Also the form parameters entered along with file upload should be shown back. So the user does not have to re enter the previously entered values. Coming up in next post...