Spring 3.2 MVC, Upload File in a specific folder

In this Spring 3.2 MVC tutorial, you will learn about uploading file in a specified folder.

Spring 3.2 MVC, Upload File in a specific folder

Spring 3.2 MVC, Upload File in a specific folder

In this Spring 3.2 MVC tutorial, you will learn about uploading file in a specified folder.

In the given below example, you can upload any kind of file for example images, text files, Pdfs etc. First you need to seek file of any type which you are going to upload through browse button. And after uploading file, it saves the file in the defined folder and it will show you the path where it saves the file.

Application Flow

When you execute the application, first page would be:

When you click on the above shown hyperlink, you will get  :

If you click Upload button without browsing the file, you will get :

After browsing the file, when you hit the Upload button, you will get the following page :

The above page is showing the directory(directory path) where the file is actually uploaded. Also, in consol, you can see the uploaded file name :

Project Structure

Project structure in eclipse, including jar files, is shown below :

CODE

Code is shown below :

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3.2FileUpload</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/forms/*</url-pattern>
</servlet-mapping>

</web-app>

dispatcher-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: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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />

<context:component-scan base-package="net.roseindia.controller" />

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>

<!-- Configure the multipart resolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000" />
<property name="uploadTempDir" ref="uploadDirResource" />
</bean>

<bean id="uploadDirResource" class="org.springframework.core.io.FileSystemResource">
<constructor-arg>
<value>C:/upload_test</value>
</constructor-arg>
</bean>


</beans>

index.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>Spring 3.2 MVC, File Upload Example</title>
</head>
<body bgcolor="#FF8040">
<%response.sendRedirect("forms/uploadfileindex.jsp"); %>
</body>
</html>

UploadFileController.java

package net.roseindia.controller;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.BindException;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import net.roseindia.model.UploadItem;

@Controller
public class UploadFileController {
private String uploadFolderPath;
ServletConfig config;

public String getUploadFolderPath() {
return uploadFolderPath;
}

public void setUploadFolderPath(String uploadFolderPath) {
this.uploadFolderPath = uploadFolderPath;
}

@RequestMapping(value = "/uploadFilePage")
public String getUploadForm(Model model) {
model.addAttribute(new UploadItem());
return "/uploadFilePage";
}

@RequestMapping(value = "/uploadfile")
public String create(UploadItem uploadItem, HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors,
HttpSession session) {
try {

MultipartFile filea = uploadItem.getFileData();

InputStream inputStream = null;
OutputStream outputStream = null;
if (filea.getSize() > 0) {
inputStream = filea.getInputStream();
outputStream = new FileOutputStream("C:\\upload_test\\"
+ filea.getOriginalFilename());
System.out.println("==========Uploaded File Name=========");
System.out.println(filea.getOriginalFilename());
System.out.println("====================================");
int readBytes = 0;
byte[] buffer = new byte[8192];
while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
session.setAttribute("success", "File Uploaded Successfully");
session.setAttribute("uploadFile", "C:\\upload_test\\"
+ filea.getOriginalFilename());
}
} catch (Exception e) {
e.printStackTrace();
}
return "uploadfileindex";
}

@RequestMapping("/uploadfileindex")
public String showRegistration() {
return "uploadfileindex";
}

}

UploadItem.java

package net.roseindia.model;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class UploadItem {
private String filename;
private CommonsMultipartFile fileData;

public String getFilename() {
return filename;
}

public void setFilename(String filename) {
this.filename = filename;
}

public CommonsMultipartFile getFileData() {
return fileData;
}

public void setFileData(CommonsMultipartFile fileData) {
this.fileData = fileData;
}
}

uploadfileindex.jsp

<%@page contentType="text/html;charset=UTF-8"%>
<%@page pageEncoding="UTF-8"%>
<%@ page session="true"%>
<%@taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<META http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Welcome</title>
</head>
<body bgcolor="#BB940">
<h1>Spring 3.2 MVC File Upload Example</h1>
<hr />
<h2><a href="uploadFilePage">Click here to upload File</a></h2>
<%
if (session.getAttribute("uploadFile") != null
&& !(session.getAttribute("uploadFile")).equals("")) {
%>
<h3>Uploaded File</h3>
<br>
<%=session.getAttribute("success")%>
<br>
<%=session.getAttribute("uploadFile")%>
<%
session.removeAttribute("uploadFile");
}
%>
</body>
</html>

uploadFilePage.jsp

<%@page contentType="text/html;charset=UTF-8"%>
<%@page pageEncoding="UTF-8"%>
<%@ page session="false"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<head>
<META http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Upload Example</title>
<script language="JavaScript">
function Validate()
{
var image =document.getElementById("image").value;
if(image==''){
alert("Please enter Image Path");
document.getElementById("image").focus();
return false;
}
}
</script>
</head>
<body bgcolor="#BB940">
<form:form modelAttribute="uploadItem" name="frm" method="post"
enctype="multipart/form-data" onSubmit="return Validate();"
action="uploadfile">
<fieldset><legend>Upload File</legend>
<table>
<tr>
<td><form:label for="fileData" path="fileData">File</form:label><br />
</td>
<td><form:input path="fileData" id="image" type="file" /></td>
</tr>
<tr>
<td><br />
</td>
<td><input type="submit" value="Upload" /></td>
</tr>
</table>
</fieldset>
</form:form>
</body>
</html>

Download Source Code