Spring MVC file upload – single and Multiple files upload
In Spring MVC application, it is very much common that we need to upload the file.
So it provides a simple way for doing it.
We need to follow below 4 steps to make the file upload successfully in Spring MVC
1)Add the file upload field in the form using input type as file
- <input type=”file” name=”uploadFile”/>
<input type=”file” name=”uploadFile”/>
2)The form must be configured to submit the file in the request by providing encype as multipart/form-data as below
- <form method="POST" action="uploadFile" enctype="multipart/form-data">
<form method="POST" action="uploadFile" enctype="multipart/form-data">
3)Handler Method needs to be configured to handle the uploaded file, so handler method must have a parameter of type MultipartFile as below
- public @ResponseBody String uploadFileHandler(@RequestParam("name") String name, @RequestParam("file") MultipartFile file)
public @ResponseBody String uploadFileHandler(@RequestParam("name") String name, @RequestParam("file") MultipartFile file)
4)Define the bean of type MultipartResolver and it has 2 implementations
CommonsMultipartResolver and StandardServletMultipartResolver
Since Dsipatcher servlet has declared a field called multipartResolver, we need to define a bean with the same name so that it will be injected to DispatcherServlet.
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
Lets develop an application
User uploads the file from the form and same file will be saved in the server by the handler.
Project structure
Create the pom.xml with required dependencies
We will add apache file upload and file io dependencies as below
- <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/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>Spring</groupId>
- <artifactId>FileUpload</artifactId>
- <packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
- <name>FileUpload Maven Webapp</name>
- <url>http://maven.apache.org</url>
- <properties>
- <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>3.8.1</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${org.springframework.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${org.springframework.version}</version>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.5</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.servlet.jsp.jstl</groupId>
- <artifactId>javax.servlet.jsp.jstl-api</artifactId>
- <version>1.2.1</version>
- </dependency>
- <!-- Apache Commons FileUpload -->
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.3.1</version>
- </dependency>
- <!-- Apache Commons IO -->
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.4</version>
- </dependency>
- <dependency>
- <groupId>taglibs</groupId>
- <artifactId>standard</artifactId>
- <version>1.1.2</version>
- </dependency>
- </dependencies>
- <build>
- <finalName>SpringFileUpload</finalName>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>2.5.1</version>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Spring</groupId> <artifactId>FileUpload</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>FileUpload Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <org.springframework.version>4.2.0.RELEASE</org.springframework.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>javax.servlet.jsp.jstl-api</artifactId> <version>1.2.1</version> </dependency> <!-- Apache Commons FileUpload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- Apache Commons IO --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies> <build> <finalName>SpringFileUpload</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
Create the web.xml
- <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
- version="3.1">
- <display-name>FileUpload</display-name>
- <!-- Spring MVC dispatcher servlet -->
- <servlet>
- <servlet-name>mvc-dispatcher</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- /WEB-INF/spring-mvc.xml,
- </param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>mvc-dispatcher</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>FileUpload</display-name> <!-- Spring MVC dispatcher servlet --> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring-mvc.xml, </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
Create the spring configuration file
Now add the multipartResolver bean in the configuration file so that spring can handle multippart requests like file upload.
- <?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:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.2.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
- <context:component-scan base-package="com.kb.*" />
- <mvc:annotation-driven />
- <bean id="viewResolver"
- class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/WEB-INF/pages/" />
- <property name="suffix" value=".jsp" />
- </bean>
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <!-- setting maximum upload size in KB -->
- <property name="maxUploadSize" value="100000" />
- </bean>
- </beans>
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <context:component-scan base-package="com.kb.*" /> <mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- setting maximum upload size in KB --> <property name="maxUploadSize" value="100000" /> </bean> </beans>
Create the view page
One for single file and other for multiple files upload
uploadSingleFile.jsp
- <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
- pageEncoding="ISO-8859-1"%>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
- <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
- <!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>Hello</title>
- </head>
- <body>
- <form method="POST" action="uploadSingleFile" enctype="multipart/form-data">
- File to Upload: <input type="file" name="file"><br />
- Name: <input type="text" name="name"><br /> <br />
- <input type="submit" value="Upload">
- </form>
- </body>
- </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <!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>Hello</title> </head> <body> <form method="POST" action="uploadSingleFile" enctype="multipart/form-data"> File to Upload: <input type="file" name="file"><br /> Name: <input type="text" name="name"><br /> <br /> <input type="submit" value="Upload"> </form> </body> </html>
uploadMultipleFile.jsp
- <%@ 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>
- <form method="POST" action="uploadMultipleFiles" enctype="multipart/form-data">
- File1 to upload: <input type="file" name="file"><br />
- Name: <input type="text" name="name"><br /> <br />
- File2 to upload: <input type="file" name="file"><br />
- Name: <input type="text" name="name"><br /> <br />
- <input type="submit" value="Upload">
- </form>
- </body>
- </html>
<%@ 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> <form method="POST" action="uploadMultipleFiles" enctype="multipart/form-data"> File1 to upload: <input type="file" name="file"><br /> Name: <input type="text" name="name"><br /> <br /> File2 to upload: <input type="file" name="file"><br /> Name: <input type="text" name="name"><br /> <br /> <input type="submit" value="Upload"> </form> </body> </html>
Create the controller
- package com.kb.controllers;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import javax.servlet.ServletContext;
- 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.bind.annotation.ResponseBody;
- import org.springframework.web.context.ServletContextAware;
- import org.springframework.web.multipart.MultipartFile;
- import org.springframework.web.servlet.ModelAndView;
- @Controller
- public class FileUploadController implements ServletContextAware {
- private ServletContext servletContext;
- @RequestMapping(value = "/uploadSingleFile", method = RequestMethod.GET)
- public ModelAndView uploadSingleFileFormDisplay() {
- return new ModelAndView("uploadSingleFile");
- }
- @RequestMapping(value = "/uploadMultipleFiles", method = RequestMethod.GET)
- public ModelAndView uploadMultipleFilesFormDisplay() {
- return new ModelAndView("uploadMultipleFiles");
- }
- //Handle the single file upload
- @RequestMapping(value = "/uploadSingleFile", method = RequestMethod.POST)
- public @ResponseBody String uploadSingleFileHandler(@RequestParam("name") String filename,
- @RequestParam("file") MultipartFile file) {
- //file handling to upload it in the server path
- if (!file.isEmpty()) {
- try {
- byte[] bytes = file.getBytes();
- BufferedOutputStream stream =
- new BufferedOutputStream(new FileOutputStream(new File(servletContext.getRealPath("/")+"/"+filename)));
- stream.write(bytes);
- stream.close();
- return "You successfully uploaded " + filename + "!";
- } catch (Exception e) {
- return "You failed to upload " + filename + " => " + e.getMessage();
- }
- } else {
- return "You failed to upload " + filename + " because the file was empty.";
- }
- }
- //Handle the multiple files upload
- @RequestMapping(value = "/uploadMultipleFiles", method = RequestMethod.POST)
- public @ResponseBody String uploadMultipleFilesHandler(@RequestParam("name") String[] filenames,
- @RequestParam("file") MultipartFile[] files) {
- //file handling to upload it in the server path
- if (files.length != filenames.length)
- return "Required information missing";
- String message = "";
- for (int i = 0; i < files.length; i++) {
- MultipartFile file = files[i];
- String filename = filenames[i];
- try {
- byte[] bytes = file.getBytes();
- BufferedOutputStream stream =
- new BufferedOutputStream(new FileOutputStream(new File(servletContext.getRealPath("/")+"/"+filename)));
- stream.write(bytes);
- stream.close();
- message = message + "You successfully uploaded file=" + filename
- + "<br />";
- } catch (Exception e) {
- return "You failed to upload " + filename + " => " + e.getMessage();
- }
- }
- return message;
- }
- public void setServletContext(ServletContext servletContext) {
- this.servletContext=servletContext;
- }
- }
package com.kb.controllers; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import javax.servlet.ServletContext; 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.bind.annotation.ResponseBody; import org.springframework.web.context.ServletContextAware; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; @Controller public class FileUploadController implements ServletContextAware { private ServletContext servletContext; @RequestMapping(value = "/uploadSingleFile", method = RequestMethod.GET) public ModelAndView uploadSingleFileFormDisplay() { return new ModelAndView("uploadSingleFile"); } @RequestMapping(value = "/uploadMultipleFiles", method = RequestMethod.GET) public ModelAndView uploadMultipleFilesFormDisplay() { return new ModelAndView("uploadMultipleFiles"); } //Handle the single file upload @RequestMapping(value = "/uploadSingleFile", method = RequestMethod.POST) public @ResponseBody String uploadSingleFileHandler(@RequestParam("name") String filename, @RequestParam("file") MultipartFile file) { //file handling to upload it in the server path if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(servletContext.getRealPath("/")+"/"+filename))); stream.write(bytes); stream.close(); return "You successfully uploaded " + filename + "!"; } catch (Exception e) { return "You failed to upload " + filename + " => " + e.getMessage(); } } else { return "You failed to upload " + filename + " because the file was empty."; } } //Handle the multiple files upload @RequestMapping(value = "/uploadMultipleFiles", method = RequestMethod.POST) public @ResponseBody String uploadMultipleFilesHandler(@RequestParam("name") String[] filenames, @RequestParam("file") MultipartFile[] files) { //file handling to upload it in the server path if (files.length != filenames.length) return "Required information missing"; String message = ""; for (int i = 0; i < files.length; i++) { MultipartFile file = files[i]; String filename = filenames[i]; try { byte[] bytes = file.getBytes(); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(servletContext.getRealPath("/")+"/"+filename))); stream.write(bytes); stream.close(); message = message + "You successfully uploaded file=" + filename + "<br />"; } catch (Exception e) { return "You failed to upload " + filename + " => " + e.getMessage(); } } return message; } public void setServletContext(ServletContext servletContext) { this.servletContext=servletContext; } }
Added first 2 methods to display the view page.
Then next 2 methods to handle the file upload.
Deploy the application
Access the below url
http://localhost:8080/SpringFileUpload/uploadSingleFile
Now Choose any file in your system and try to upload it
I am uploading example.pdf file
Give the name as you want in the Name box.
Click on Upload
Now access the below url to upload multiple files
http://localhost:8080/SpringFileUpload/uploadMultipleFiles
Choose 2 files and upload them
Click on upload
Now check the server path whether files are upload in that path
All the uploaded files are present in the server path where our application is deployed as shown below
And that path is E:\java\apache-tomcat-8.0.5-windows-x64\apache-tomcat-8.0.5\webapps\SpringFileUpload