Spring MVC file upload example


In this post, we will see Spring MVC file upload example. We have already seen struts 2 file upload example.

Spring MVC tutorial:

Spring MVC uses Apache common FileUpload API to upload file. It is very easy to configure file upload in Spring MVC.

Project structure for below example:

Steps for Spring MVC file upload example:

1) Create dynamic web project using maven named “SpringMVCFileUploadExample”.

2) Maven dependencies

It requires spring dependency as we have put in spring mvc hello world example. It requires apache common io jars too, so we need to put following dependency for it.

So pom.xml will be as below

3) Create model,controller and validator

Create a class model called “FileUpload.java” in packge org.arpit.java2blog.model and it will have variable of type MultiFilePart.

Create class FileUploadController.java in package org.arpit.java2blog.controller . It is spring controller and to understand more above controller, please go through Spring MVC hello world example.

We need validator for validations such as no files selected. Create validator FileUploadValidator.java in package org.arpit.java2blog.validator

4)  Spring configuration

It will have simple web.xml for spring as in hello world example.

We need to change in “springmvc-dispatcher-servlet.xml” as below

We need to declare multipartResolver bean in above file to enable file upload. We have also put bean entry of validator.

5) Views

Finally create views for file upload form and file upload success page. Create fileUploadForm.jsp in /WEB-INF/JSP/ folder


create filUploadSuccess.jsp /WEB-INF/JSP/ folder

6) Its time for maven build

   Provide goals as clean install (given below) and click on run

7) Run the application

Right click on project -> run as -> run on server
Select apache tomcat and click on finish
You will see below screen:
URL : http://localhost:8080/SpringMVCFileUploadExample/fileUploadForm.htm

 If you directly click on upload button without selecting any file, it will give you error as “Please select a file”

Lets upload “config.properties” 

If your file is successfully uploaded, you will see below screen.

You can check in the folder whose path you have given in above application.

8) Source code

click to begin
20KB .zip

Bingo!! We are done with Spring MVC file upload example.


Add Comment