Spring MVC File Upload Example Tutorial
File Uploading is a very common task in any web application. Today we will learn about Spring File upload, specifically Spring MVC File Upload for single and multiple files.
Spring uses MultipartResolver interface to handle the file uploads in web application. Below are two of the implementation :
- StandardServletMultipartResolver – Servlet 3.0 multipart request parsing.
- CommonsMultipartResolver – Classic commons-fileupload.jar
Tools used in this article :
-
- Spring 4.3.5.RELEASE
- Maven 3
- Tomcat 7
1. Project Structure
2. Project Dependency
First of all we need to add project dependency in our pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.learningsolo.spring</groupId> <artifactId>springFileUpload</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>FileUpload</name> <description>FileUpload</description> <properties> <jdk.version>1.8</jdk.version> <spring.version>4.3.7.RELEASE</spring.version> <jstl.version>1.2</jstl.version> <servletapi.version>3.1.0</servletapi.version> <logback.version>1.1.3</logback.version> <jcl.slf4j.version>1.7.12</jcl.slf4j.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <!-- compile only, deployed container will provide this --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servletapi.version}</version> <scope>provided</scope> </dependency> <!-- Logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${jcl.slf4j.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.0.0</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> </configuration> </plugin> </plugins> </build> </project> |
3. Spring MVC configuration
To enable file upload we will add MultiPart bean in our spring mvc configuration file springDispatcherContext.xml org.springframework.web.multipart.commons.CommonsMultipartResolver
Our final Spring configuration file looks like below.
springDispatcherContext.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?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:security="http://www.springframework.org/schema/security" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <mvc:annotation-driven /> <context:component-scan base-package="com.learningsolo.spring*" /> <mvc:resources mapping="/resources/**" location="/resources/" /> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- File Upload Configuration Bean Details --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="1000000000" /> </bean> </beans> |
Notice I am setting max upload file size for CommonsMultiPartResolver using “maxUploadSize”
4. Spring File Upload Controller Class
Controller class is the main class of our Spring MVC File Upload example which controls teh file upload process. Controller class should have handler method to return view and also to process file upload.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package com.learningsolo.spring; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller public class FileUploadController { @RequestMapping(value = "/welcome", method = RequestMethod.GET) public ModelAndView index() { return new ModelAndView("upload"); } @RequestMapping(value = "/upload", method = RequestMethod.POST) public ModelAndView singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { if (file.isEmpty()) { redirectAttributes.addFlashAttribute("message", "Please select a file to upload"); return new ModelAndView("upload","message", "Please select a file to upload"); } try { // Get the file and save it somewhere byte[] bytes = file.getBytes(); Path path = Paths.get("C://temp//" + file.getOriginalFilename()); Files.write(path, bytes); redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'"); } catch (IOException e) { redirectAttributes.addFlashAttribute("message", "Failure occured during upload '" + file.getOriginalFilename() + "'"); e.printStackTrace(); } return new ModelAndView("upload","message", "You successfully uploaded '" + file.getOriginalFilename() + "'"); } } |
5. Spring View – upload.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <h1>Spring MVC file upload example</h1> <form method="POST" action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="Submit" /> </form> <h1>Upload Status</h1> <h2>Message : ${message}</h2> </body> </html> |
6. Web.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>SpringFileUpload</display-name> <!-- <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> --> <servlet> <servlet-name>springdispatcher_srr</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springDispatcherContext.xml</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springdispatcher_srr</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> |
7. Spring File upload Result
Type below url in browser and open welcome page to upload file.
http://localhost:8080/springFileUpload/welcome
Upload success:
Also Read about Spring MVC Excel file upload to database here.
Download Sample from GitHub.com