Spring MVC File Upload Example

In this tutorial you will learn how to implement single/multiple file upload in Spring MVC.You will also learn how to display the uploaded images without being saved in web application directory.

Required Jars files

Add following jars to the WEB-INF/lib.

  • spring core module
  • spring web module
  • commons-fileupload-1.1.1.jar
  • commons-io-1.1.jar
  • jstl-1.2.jar

spring-file-upload-jar

Define Bean For Form

We need to define bean for Form/Model object.This bean contains a List of org.springframework.web.multipart.MultipartFile objects.

package com.startwithjava;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class FileUploadForm {
	private List<MultipartFile> files;
	
	public List<MultipartFile> getFiles() {
		return files;
	}

	public void setFiles(List<MultipartFile> files) {
		this.files = files;
	}
	
}

Define Controller

FileController.java contains the logic for uploading files,if there some other fields you can define there in Form bean.

package com.startwithjava;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;
@Controller
public class FileController {
	private String saveDirectory = "F:/uploads/";
	@RequestMapping(value="/save", method = RequestMethod.POST)
	public String upload(@ModelAttribute("uploadForm") FileUploadForm uploadForm,ModelMap map){
		byte fileBytes[];
		FileOutputStream fos=null;
		List<MultipartFile> list = uploadForm.getFiles();
		List<String> filenames = new ArrayList<String>();
	    if(list!=null && list.size()>0){
    	 for (MultipartFile multipartFile : list) {
                String fileName = multipartFile.getOriginalFilename();
                System.out.println("File Name--"+fileName);
                File file = new File(saveDirectory + multipartFile.getOriginalFilename());
				
				try {
					fos = new FileOutputStream(file);
					fileBytes = multipartFile.getBytes();
					fos.write(fileBytes);
					filenames.add(fileName);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
            }
	    }
	    map.addAttribute("fileList", filenames);
		return "files";
	}

}

index.jsp

  
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring MVC Multiple File Upload By StartWithJava<</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
    //add more file components if Add is clicked
    $('#addFile').click(function() {
        var fileIndex = $('#fileTable tr').children().length - 1;
        $('#fileTable').append(
                '<tr><td>'+
                '   <input type="file" name="files['+ fileIndex +']" />'+
                '</td></tr>');
    });
     
});
</script>
</head>
<body>
<h1>Spring Multiple File Upload</h1>
 
<form:form method="post" action="save"
        modelAttribute="uploadForm" enctype="multipart/form-data">
 
    <p>Select files to upload. Click on <b>Add More</b> button to add more files.</p>
 
    <input id="addFile" type="button" value="Add More" />
    <table id="fileTable">
        <tr>
            <td><input name="files[0]" type="file" /></td>
        </tr>
        <tr>
            <td><input name="files[1]" type="file" /></td>
        </tr>
    </table>
    <br/><input type="submit" value="Upload" />
</form:form>
</body>
</html>

Define Configuration files

There are two configuration files web.xml and spring1-servlet.xml.For using spring MultipartFile we need to define following bean entry in spring1-servlet.xml file.

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
         <!-- setting maximum upload size -->
        <property name="maxUploadSize" value="20971520" />
    </bean>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
    <param-name>contextConfigLocation</param-name>        
<param-value>/WEB-INF/spring1-servlet.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

	<servlet>
		<servlet-name>spring1</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring1</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

spring1-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
	<context:component-scan base-package="com.startwithjava"/>
   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
              <property name="prefix">
                 <value>/WEB-INF/jsp/</value>
              </property>
              <property name="suffix">
                 <value>.jsp</value>
              </property>
        </bean>
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
         <!-- setting maximum upload size -->
        <property name="maxUploadSize" value="20971520" />
    </bean>
</beans>

Download Source Code

Download Spring FileUploader

Leave a Reply