Spring 3 MVC Upload File in a specific folder

Spring 3 MVC Upload File in a specific folder


Posted in : Spring Posted on : April 13, 2011 at 5:28 PM Comments : [ 0 ]

Spring 3 is a open source application framework for the java platform. Spring MVC is the web framework of the Spring framework.

Spring 3 MVC Upload File in a specific folder

In the given below tutorial, you will learn how to upload any type of file in a folder specified by you.

In the given below example, you can upload any kind of file for example images, text files, Pdfs etc.  First you need to seek the any type of file which you are going to upload. 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 click on File upload hyperlink :

When you click on the above hyperlink :

If you click upload button without browsing the file :

After Successful Upload, it will show you the following message & the path  where it actually uploaded :

You can see the different type of file uploaded with this application in defined folder :

The project hierarchy of the application :

The jar file used is give below :

CODES

web.xml (/Spring3MvcUploadFile/WebContent/WEB-INF/web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">

<display-name>Spring3MvcUploadFile</display-name>
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

dispatcher-servlet.xml (/Spring3MvcUploadFile/WebContent/WEB-INF/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.controllers" />

<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:/test111</value>
</constructor-arg>
</bean>


</beans>

index.jsp (/Spring3MvcUploadFile/WebContent/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, MVC Examples</title>
</head>
<body bgcolor="#FF8040">
<h1>Spring 3 MVC File Upload to a specific folder</h1>
<ul>
<li><a href="forms/uploadfileindex.html">File Upload</a></li>
</ul>
</body>
</html>

UploadFileController.java (/Spring3MvcUploadFile/src/net/roseindia/controllers/UploadFileController.java)

package net.roseindia.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import javax.servlet.ServletConfig;
import java.io.FileOutputStream;

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

import net.roseindia.form.UploadItem;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value = "/uploadfile")
public class UploadFileController {
private String uploadFolderPath;
ServletConfig config;

public String getUploadFolderPath() {
return uploadFolderPath;
}

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

@RequestMapping(method = RequestMethod.GET)
public String getUploadForm(Model model) {
model.addAttribute(new UploadItem());
return "/uploadfile";
}

@RequestMapping(method = RequestMethod.POST)
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();
// File realUpload = new File("C:/");
outputStream = new FileOutputStream("C:\\test111\\"
+ filea.getOriginalFilename());
System.out.println("====22=========");
System.out.println(filea.getOriginalFilename());
System.out.println("=============");
int readBytes = 0;
byte[] buffer = new byte[8192];
while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
System.out.println("===ddd=======");
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
session.setAttribute("success", "File Uploaded Successfully");
session.setAttribute("uploadFile", "C:\\test111\\"
+ filea.getOriginalFilename());
}
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/forms/uploadfileindex";
}
}

UploadFileIndexController.java (/Spring3MvcUploadFile/src/net/roseindia/controllers/UploadFileIndexController.java)

package net.roseindia.controllers;

import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/uploadfileindex")
public class UploadFileIndexController {

// Display the form on the get request
@RequestMapping(method = RequestMethod.GET)
public String showRegistration(Map model) {
return "uploadfileindex";
}

// Process the form.
@RequestMapping(method = RequestMethod.POST)
public String processRegistration(BindingResult result) {
return "uploadfileindex";
}
}

UploadItem.java  (/Spring3MvcUploadFile/src/net/roseindia/form/UploadItem.java)

package net.roseindia.form;

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;
}
}

uploadfile.jsp (/Spring3MvcUploadFile/WebContent/WEB-INF/views/uploadfile.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="#FF8040">
<form:form modelAttribute="uploadItem" name="frm" method="post"
enctype="multipart/form-data" onSubmit="return Validate();">
<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>

uploadfileindex.jsp (/Spring3MvcUploadFile/WebContent/WEB-INF/views/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="#FF8040">
<h2><a href="uploadfile.jsp">Upload any file in defined folder</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>

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics