Spring 3 MVC upload ,view and save image

Spring 3 MVC upload ,view and save image


Posted in : Spring Posted on : April 12, 2011 at 5:46 PM Comments : [ 0 ]

In this tutorial, you will learn how to upload a image using Spring 3 MVC.

Spring 3 MVC upload ,view and save image

In this tutorial, you will learn how to upload a image using Spring 3 MVC.

In the given below example, first you need to seek the image file which you are going to upload. And after uploading file, it save the file in the defined folder and fetch the file from that folder to show you the uploaded image preview.

Application Flow

 

 

When You click on the "File Upload" hyperlink you will get the following :

 

 

When you click on the Upload Example Hyperlink, it will show :

 

When you browse image & upload, it will redirect you to the following page :

 

 

If look at the console, you will get the following :

 

The project hierarchy of the application :

 

The jar file used is give below :

 

CODES

web.xml ( /Spring3UploadImage/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>Spring3UploadImage</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 (/Spring3UploadImage/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 (/Spring3UploadImage/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>
<h1>Spring 3 MVC Image Upload Example</h1>
<ul>
<li><a href="forms/uploadfileindex.html">File Upload</a></li>
</ul>
</body>
</html>

UploadFileController.java (/Spring3UploadImage/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.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.BindException;

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

@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("uploadFile", "C:\\test111\\"
+ filea.getOriginalFilename());
}
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/forms/uploadfileindex";
}
}

UploadFileIndexController.java (/Spring3UploadImage/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 (/Spring3UploadImage/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 (/Spring3UploadImage/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!=''){
var checkimg = image.toLowerCase();
if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.jpeg|\.JPEG)$/)){
alert("Please enter Image File Extensions .jpg,.png,.jpeg");
document.getElementById("image").focus();
return false;
}
}
return true;
} 
</script>
</head>
<body>
<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 (/Spring3UploadImage/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>
<h2><a href="uploadfile.jsp">Upload Example</a></h2>
<%
if (session.getAttribute("uploadFile") != null
&& !(session.getAttribute("uploadFile")).equals("")) {
%>
<h3>Uploaded File</h3>
<br>
<img src="<%=session.getAttribute("uploadFile")%>" alt="Upload Image" />

<%
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