Wednesday, April 27, 2011

Upload Files with Spring MVC

Have you ever tried to upload a file as part of a form to be submited?
In my case I have a form to add or update products, and each product must have an image (JPG file), besides the regular information related to each product: Name, Description, etc.
Then, we need a form with some inputs and a method on one of my controllers to handle this request and we're set.

This topic is really simple to cover, despite of the fact is poorly covered by the official documentation.
Steps
Add entries on your POM
Add a MultipartResolver in your Web Application Context
On your form don't forget to include enctype attribute and make it POST

Add your input type file as regular HTML


In your controller add a method to handle with all params
I'm using FileUtils to save the uploaded file :D
Look carefully to this parameter @RequestParam("productImage") matches to

And you're all set! Easy, Isn't it?

No comments:

Post a Comment