Spring MVC: Handling File Upload

Concept Overview

Please see this tutorial for an introduction to Spring MVC. In this tutorial we look at how to upload files using spring MVC framework. There are three things that need to be done to be enable file upload in a form.

  1. Add a file upload field in the form. This can be easily achieved by using a input element of type file.
    	   
    	

    . The form needs to be configured to submit files. This is achieved by changing the form type to multipart/form-data

  2. Handle uploaded file – To handle the uploaded file, the handler method needs to be declared with a parameter of type MultipartFile. This parameter accepts the uploaded file. Look at the method signature of the handler method in the example below
  3. Give the DispatcherServlet a multipart resolver (to take care of the MultipartFile parameter that we passed in 2 above). The DispatcherServlet declares a field called multipartResolver. Declare a bean of same name and it will be injected in the DispatcherServlet. Spring provides two implementations of MultipartResolvers – CommonsMultipartResolver and StandardServletMultipartResolver

The example below shows how to present a form that allows the user to upload an image.


Required Libraries
  • commons-beanutils.jar
  • commons-collections.jar
  • commons-digester.jar
  • commons-fileupload.jar
  • commons-io.jar
  • hibernate-validator-4.2.0.Final.jar
  • jstl-1.2.jar
  • org.springframework.aop.jar
  • org.springframework.asm.jar
  • org.springframework.beans.jar
  • org.springframework.context.jar
  • org.springframework.context.support.jar
  • org.springframework.core.jar
  • org.springframework.expression.jar
  • org.springframework.web.jar
  • org.springframework.web.servlet.jar
  • retrotranslator-runtime-1.2.3.jar
  • servlet-api-2.5.jar
  • slf4j-api-1.6.1.jar
  • validation-api-1.0.0.GA.jar



Source Code

Create the Person class which models a Person with his name and age. This represents the model in MVC pattern.

Create the PersonService class with a method to fetch a list of all the persons (see lines 19-21 below) and also to add a new Person (see lines 23-25 below). PersonService class will be used by PersonController (described later) to add a new Person and also fetch the list of all persons.

Create the PersonController class. This class is the Controller in MVC pattern and is declared as such by using the
@Controller
annotation (see line 22 below).

When a request URL ends with
/person/add
then Spring MVC passes the control to
addPersonFromForm
method (see lines 51-74 below) by using the
@RequestMapping
annotation (see line 50 below).

In particular, note that the request parameter called ‘image’ is handled using
MultipartFile
(see line 53 below). This is used in uploading the image file.

Validate that the image is of type JPEG(see line 56-62 and lines 76-80 below).

Finally, save the image to the file system (see line 65). This file is stored in the servlet context path of the web application (see lines 88-100 below).

This demonstrates the handling of file uploads.

Create the new_person.jsp as shown below which allows the user to add a new Person. This represents the view in MVC pattern.

Set the encoding type as
multipart/form-data
to allow for file uploading (see line 9 below)

Create and HTML form to take name, age and image of the person as inputs (see lines 10-31 below).

When the ‘Submit’ button is pressed, then call the ‘/springmvcfileupload/person/add’ URL to create a new Person (see line 8 below).

Create the person_list.jsp as shown below which displays the list of all Persons. This represents the view in MVC pattern.

Get the list of persons by using the name of the model
persons
(see line 17 below). Note that this model was set in PersonController.showPersonListPage() method with the same model name.

Iterate the list persons and display the list in a table (see lines 18-23 below).

Create the web.xml configuration as shown below.

Create a servlet mapping with name
person
(see lines 13-16 below) and define the corresponding servlet using Spring
DispatcherServlet
class (see lines 7-11 below).

Note that Spring automatically will look for a configuration file called
person-servlet.xml
corresponding to the servlet mapping name person. We shall describe the details of
person-servlet.xml
later.

Create the Spring configuration by the name
person-servlet.xml
as shown below.

Configure Spring such that annotation based wiring will be used (see lines 14-15 below).

Configure Spring default validator which will perform validations (see line 17 below) defined in Person class

Configure Spring such that the prefix
/views
and the suffix
.jsp
should be added to the name of the view JSPs specified in various methods in PersonController (see lines 19-27 below).

To handle file uploads, configure the MultipartResolver along with the maximum permissible file size (see lines 30-32 below).

Running Sample Program

This sample program has been packaged as a jar installer which will copy the source code (along with all necessary dependencies)on your machine and automatically run the program for you as shown in the steps below. As this sample program contains Java Server Pages (JSPs), you will need Java Development Kit (JDK preferably 1.5 or higher) on your machine so that the JSPs can be complied locally. Note that no other setup is required on your machine! Also please ensure that the port 8080 is not being used by any other program on your machine.

Download And Automatically Run Sample Program
  • Save the springmvcfileupload-installer.jar on your machine
  • Execute/Run the jar using Java Runtime Environment


  • (Alternatively you can go the folder containing the springmvcfileupload-installer.jar and execute the jar using
    java -jar springmvcfileupload-installer.jar
    command)

  • You will see a wizard as shown below. Enter the location of Java Development Kit (JDK) and Click ‘Next’ button.
  • You will see a wizard page as shown below
  • Enter the location of the directory where you want the program to install and run (say, C:\Temp)
  • The installer will copy the program on your machine and automatically start the inbuilt webserver on your machine as shown below.
  • Go to the URL http://localhost:8080/springmvcfileupload/person?new as shown below
  • Enter the values for the Person as shown below. Also upload a jpeg image.
  • On pressing the Submit button, verify that the newly added person is shown in the list
  • Go the folder where you saved this program (e.g. C:\Temp and then further go to springmvcfileupload\WebContent folder. Verify that the image uploaded by you is saved to the file system.
  • Browsing the Program

    This source code for this program is downloaded in the folder specified by you (say, C:\Temp) as an eclipse project called
    springmvcfileupload
    . All the required libraries have also been downloaded and placed in the same location. You can open this project from Eclipe IDE and directly browse the source code. See below for details of the project structure.

    4 thoughts on “Spring MVC: Handling File Upload”

    1. Hi. Thanks for your post I have a question, where can I place the files, somewhere different to temp files, some permanent folder or something like that? Thanks

      Reply
    2. Can i read/parse a xml file within the save method? I dont wanna save the file to the disk. just want to parse and write it to db

      Reply
    3. Hi,
      I find this example pretty useful but at the same time, I would like to ask some help about displaying image from the folder we have added.
      I couldn’t manage to achieve this and a example or a source link would be amazing after this great example.

      Thanks!!

      Reply

    Leave a Reply to Ugurcan Cetin Cancel reply