This tutorial shows an example on how to upload a single file using Spring MVC 4.x. You may also read Spring MVC Multiple Files Upload Example

For this tutorial we will create maven based web project in Eclipse.

If you already have an idea on how to create a maven project in Eclipse will be great otherwise I will tell you here how to create a maven project in Eclipse.

Prerequisites

The following configurations are required in order to run the application

Eclipse Kepler
JDK 1.8
Tomcat 8
Have maven 3 installed and configured
Spring 4 and Apache commons IO dependencies in pom.xml

Now we will see the below steps how to create a maven based project in Eclipse
Step 1. Create a maven based web project in Eclipse

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

maven-arctype-webapp

Now enter the required fields (Group Id, Artifact Id) as shown below

Group Id : com.roytuts
Artifact Id : spring-mvc-file

Step 2. Modify the pom.xml file as shown 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>com.roytuts</groupId>
	<artifactId>spring-mvc-file</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-mvc-file Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<properties>
		<java.version>1.8</java.version>
		<spring.version>4.1.6.RELEASE</spring.version>
		<mysqlconnector.version>5.1.34</mysqlconnector.version>
	</properties>

	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
                       <groupId>org.springframework</groupId>
                       <artifactId>spring-web</artifactId>
                       <version>${spring.version}</version>
                </dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- jstl -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- mysql java connector -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysqlconnector.version}</version>
		</dependency>

                <!-- file upload -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>

		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>spring-mvc-file</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Step 3. If you see JRE System Library[J2SE-1.5] then change the version by below process

Do right-click on the project and go to Build -> Configure build path, under Libraries tab click on JRE System Library[J2SE-1.5], click on Edit button and select the appropriate jdk 1.8 from the next window. Click on Finish then Ok.

Change also the Compiler compliance level as 1.8 from Java -> Compiler.

Step 4. Now when the build process finished then modify the web.xml file with below source code

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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">

	<!-- dispatcher servlet acts as a front controller for each request/response -->
	<servlet>
		<servlet-name>spring-mvc-jdbc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- load Spring controllers while dispatcher servlet loads -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:controllers.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- map URL suffix as .html -->
	<servlet-mapping>
		<servlet-name>spring-mvc-jdbc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

Step 5. Create spring-config.xml file under src/main/resources directory with the below source code

<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 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/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

	<!-- Support annotation -->
	<mvc:annotation-driven />

</beans>

Step 6. Create controllers.xml file under src/main/resources directory

<?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"
	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">

	<import resource="classpath:spring-config.xml" />

	<!-- Scan the package where Spring Controllers are placed -->
	<context:component-scan base-package="com.roytuts.spring.controllers" />

        <!-- define multi-part bean to define handle file upload -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

	<!-- Resolves logical String-based view names to actual View types -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<!-- Where pages are kept -->
		<property name="prefix" value="/pages/" />
		<!-- What is the page extension -->
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

Step 7. Create a directory called pages under webapp directory for putting created jsp views.

Step 8. Create Spring controller class which will handle user request and response

package com.roytuts.spring.controllers;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/")
public class FileUploadController {

	public static final String ROOT = "C:/upload-dir/";

	@RequestMapping(value = "upload")
	public String uploadFile() {
		return "uploadFile";
	}

	@RequestMapping(method = RequestMethod.POST, value = "upload/file")
	public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {

		if (!file.isEmpty()) {
			try {
				if (!Files.exists(Paths.get(ROOT))) {
					try {
						Files.createDirectories(Paths.get(ROOT));
					} catch (IOException ioe) {
						ioe.printStackTrace();
					}
				}
				Files.copy(file.getInputStream(), Paths.get(ROOT, file.getOriginalFilename()));
				redirectAttributes.addFlashAttribute("msg",
						"You successfully uploaded " + file.getOriginalFilename() + "!");
			} catch (IOException | RuntimeException e) {
				redirectAttributes.addFlashAttribute("msg", "Failued to upload " + file.getOriginalFilename() + " => "
						+ e.getMessage() + String.valueOf(e));
			}
		} else {
			redirectAttributes.addFlashAttribute("msg",
					"Failed to upload " + file.getOriginalFilename() + " because it was empty");
		}

		return "redirect:/upload";
	}

}

Step 9. Now create uploadFile.jsp file under webapp/pages directory for handling single file upload

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<title>Spring MVC File Upload Example</title>
<body>
	<h2>Spring MVC File Upload Example</h2>
	<c:if test="${not empty msg}">
        ${msg}
    </c:if>
	<form method="POST" name="upload_file" enctype="multipart/form-data"
		action="<%=request.getContextPath()%>/upload/file/">
		Select File: <input type="file" name="file" /> <br /> <br /> <input
			value="Upload" type="submit" />
	</form>
</body>
</html>

Step 10. Run the application on Tomcat 8 server, you will see below outputs in the browser

When you hit the URL http://localhost:8080/spring-mvc-file/upload in the browser

spring mvc single file upload

When you browse and select a file

spring mvc single file upload

When the file successfully uploaded

spring mvc single file upload

Check the C:upload-dir

spring mvc single file upload

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *