Spring MVC Multiple File Upload Example

In this simple tutorial we will see how to implement multiple file upload in a Spring 3 MVC based application.

The requirement is simple. We have a form which displays file input component. User selects a file and upload it. Also its possible to add more file input components using Add button. Once the files are selected and uploaded, the file names are displayed on success page.

1. Maven Dependencies / Required JAR files

If you using Maven in your project for dependency management, you’ll need to add dependencies for Apache Common File upload and Apache Common IO libraries. The spring’sCommonsMultipartResolver class internal uses these library to handle uploaded content.
Add following dependencies in your maven based project to add File upload feature.

    <!-- Spring 3 MVC  -->
    <!-- Apache Commons file upload  -->
    <!-- Apache Commons IO -->
    <!-- JSTL for c: tag -->

If you have a simple web application, add following JAR files in WEB-INF/lib folder. You can download all these JARs with source code at the end of this tutorial.

2. Model – Form Object

Create a Java bean which acts as Model/Form object for our Spring application. This bean contains aList of org.springframework.web.multipart.MultipartFile objects. Spring framework provides a useful class MultipartFile which can be used to fetch the file content of uploaded file. Apart from its content, the MultipartFile object also gives you other useful information such as filename, file size etc.


package net.viralpatel.spring3.form;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class FileUploadForm {
    private List<MultipartFile> files;
    //Getter and setter methods

3. Controller – Spring Controller

Create a Spring 3 MVC based controller which handles file upload. There are two methods in this controller:

  1. displayForm – Is a used to show input form to user. It simply forwards to the page file_upload_form.jsp
  2. save – Fetches the form using @ModelAttribute annotation and get the File content from it. It creates a list of filenames of files being uploaded and pass this list to success page.


package net.viralpatel.spring3.controller;
import java.util.ArrayList;
import java.util.List;
import net.viralpatel.spring3.form.FileUploadForm;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
public class FileUploadController {
    @RequestMapping(value = "/show", method = RequestMethod.GET)
    public String displayForm() {
        return "file_upload_form";
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(
            @ModelAttribute("uploadForm") FileUploadForm uploadForm,
                    Model map) {
        List<MultipartFile> files = uploadForm.getFiles();
        List<String> fileNames = new ArrayList<String>();
        if(null != files && files.size() > 0) {
            for (MultipartFile multipartFile : files) {
                String fileName = multipartFile.getOriginalFilename();
                //Handle file content - multipartFile.getInputStream()
        map.addAttribute("files", fileNames);
        return "file_upload_success";

4. View – JSP views

Now create the view pages for this application. We will need two JSPs, one to display file upload form and another to show result on successful upload.

The file_upload_form.jsp displays a form with file input. Apart from this we have added small jquery snippet onclick of Add button. This will add a new file input component at the end of form. This allows user to upload as many files as they want (subjected to file size limit ofcourse).

Note that we have set enctype=”multipart/form-data” attribute of our <form> tag.


<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
    <title>Spring MVC Multiple File Upload</title>
$(document).ready(function() {
    //add more file components if Add is clicked
    $('#addFile').click(function() {
        var fileIndex = $('#fileTable tr').children().length - 1;
                '   <input type="file" name="files['+ fileIndex +']" />'+
<h1>Spring Multiple File Upload example</h1>
<form:form method="post" action="save.html"
        modelAttribute="uploadForm" enctype="multipart/form-data">
    <p>Select files to upload. Press Add button to add more file inputs.</p>
    <input id="addFile" type="button" value="Add File" />
    <table id="fileTable">
            <td><input name="files[0]" type="file" /></td>
            <td><input name="files[1]" type="file" /></td>
    <br/><input type="submit" value="Upload" />

Note that we defined the file input name as files[0], files[1] etc. This will map the submitted files to the List object correctly.

I would suggest you to go through this tutorial to understand how Spring maps multiple entries from form to bean: Multiple Row Form Submit using List of Beans

Second view page is to display filename of uploaded file. It simply loops through filename list and display the names.


<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <title>Spring MVC Multiple File Upload</title>
    <h1>Spring Multiple File Upload example</h1>
    <p>Following files are uploaded successfully.</p>
        <c:forEach items="${files}" var="file">

5. Spring Configuration

In Spring configuration (spring-servlet.xml) we define several important configurations. Note how we defined bean multipartResolver. This will make sure Spring handles the file upload correctly usingCommonsMultipartResolver class.


<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:annotation-config />
    <context:component-scan base-package="net.viralpatel.spring3.controller"/>
 <bean id="multipartResolver"
  <bean id="jspViewResolver"
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />

6. Output

Execute the project in Eclipse. Open following URL in browser to see file upload form.

URL: http://localhost:8080/Spring3MVC_Multiple_File_Upload_example/show.html


Select files through file dialog and press Upload button to upload. Following page will displayed with list of files being uploaded.


We have added a small Javascript snippet for Add button. This will add more file upload components to the page. Use this if you want to upload more files.

Download Source Code

SpringMVC_Multi_File_Upload_example.zip (3.6 MB)

출처 - http://viralpatel.net/blogs/spring-mvc-multiple-file-upload-example/

Posted by linuxism

댓글을 달아 주세요