Hello Friends,Hope you all are fine,its been very long i posted new post,very hactic schedule,i am going to demonstrate how we can upload file using future provided by Spring 3.0 with hibernate as a backend.
The Code is as given below :
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.springframework.web.multipart.MultipartFile;
@Entity
@Table(name="trnimage")
public class FileuploadVO {
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getIMAGE_NAME() {
return IMAGE_NAME;
}
public void setIMAGE_NAME(String iMAGE_NAME) {
IMAGE_NAME = iMAGE_NAME;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", unique = true, nullable = false)
private int ID;
@Column(name = "DATA", unique = false, nullable = false, length = 100000)
private byte[] data;
@Column(name = "IMAGE_NAME", unique = false, nullable = false, length = 100)
private String IMAGE_NAME;
@Transient
private List<MultipartFile> Files;
public List<MultipartFile> getFiles() {
return Files;
}
public void setFiles(List<MultipartFile> files) {
Files = files;
}
}
The Code is as given below :
MODEL CLASS
package org.fileupload.model;import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.springframework.web.multipart.MultipartFile;
@Entity
@Table(name="trnimage")
public class FileuploadVO {
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getIMAGE_NAME() {
return IMAGE_NAME;
}
public void setIMAGE_NAME(String iMAGE_NAME) {
IMAGE_NAME = iMAGE_NAME;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", unique = true, nullable = false)
private int ID;
@Column(name = "DATA", unique = false, nullable = false, length = 100000)
private byte[] data;
@Column(name = "IMAGE_NAME", unique = false, nullable = false, length = 100)
private String IMAGE_NAME;
@Transient
private List<MultipartFile> Files;
public List<MultipartFile> getFiles() {
return Files;
}
public void setFiles(List<MultipartFile> files) {
Files = files;
}
}
Controller :
package org.fileupload.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.fileupload.dao.fileUploadDaoImpl;
import org.fileupload.model.FileuploadVO;
import org.fileupload.service.fileUploadServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileUploadController {
//
@RequestMapping(value = "/upload.htm", method = RequestMethod.POST)
public String SaveImage(
@ModelAttribute("uploadForm") FileuploadVO uploadForm,
Model map,HttpServletRequest request ) throws IllegalStateException, IOException {
WebApplicationContext context =WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
fileUploadServiceImpl service=(fileUploadServiceImpl) context.getBean("fileuploadService");
fileUploadDaoImpl dao=(fileUploadDaoImpl) context.getBean("fileuploadDAO");
ResourceBundle rb = ResourceBundle.getBundle("resources/filePath"); //filePath is Property file
String saveDirectory = rb.getString("file.fileUploadPath");
String saveDirectory = rb.getString("file.fileUploadPath");
List<MultipartFile> listFiles = uploadForm.getFiles();
List<String> fileNames = new ArrayList<String>();
if (null != listFiles && listFiles.size() > 0) {
for (MultipartFile multipartFile : listFiles) {
String fileName = multipartFile.getOriginalFilename();
if (!"".equalsIgnoreCase(fileName)) {
// Handle file content - multipartFile.getInputStream()
multipartFile
.transferTo(new File(saveDirectory + fileName));
fileNames.add(fileName);
uploadForm.setData(fileName.getBytes());
uploadForm.setIMAGE_NAME(fileName);
service.saveImage(uploadForm);
}
}
}
map.addAttribute("files", fileNames);
return "uploadfilesuccess";
}
@RequestMapping(value = "/download.htm", method = RequestMethod.GET)
public String download( @RequestParam("id") String id,
Model map,HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {
System.out.println("id is : "+id);
WebApplicationContext context =WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
fileUploadServiceImpl service=(fileUploadServiceImpl) context.getBean("fileuploadService");
FileuploadVO f = service.downloadImg(id);
response.setContentLength(f.getData().length);
response.setHeader("Content-Disposition","attachment; filename=\"" + f.getIMAGE_NAME() +"\"");
FileCopyUtils.copy(f.getData(), response.getOutputStream());
return null;
}
@RequestMapping(value = "/download.htm", method = RequestMethod.GET)
public String download( @RequestParam("id") String id,
Model map,HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {
System.out.println("id is : "+id);
WebApplicationContext context =WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
fileUploadServiceImpl service=(fileUploadServiceImpl) context.getBean("fileuploadService");
FileuploadVO f = service.downloadImg(id);
response.setContentLength(f.getData().length);
response.setHeader("Content-Disposition","attachment; filename=\"" + f.getIMAGE_NAME() +"\"");
FileCopyUtils.copy(f.getData(), response.getOutputStream());
return null;
}
}
DAO LAYER
package org.fileupload.dao;
import org.fileupload.model.FileuploadVO;
public interface fileUploadDao {
public void saveImage(FileuploadVO fileupload);
public FileuploadVO downloadImg(String id);
}
}
package org.fileupload.dao;
import org.fileupload.model.FileuploadVO;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class fileUploadDaoImpl implements fileUploadDao{
private HibernateTemplate template;
public fileUploadDaoImpl(HibernateTemplate template) {
this.template = template;
}
@Override
public void saveImage(FileuploadVO fileupload) {
template.save(fileupload);
}
public FileuploadVO downloadImg(String id)
{
// String query = "select * from trnimage where ID = ?";
FileuploadVO file = (FileuploadVO) template.getSessionFactory().openSession().load(FileuploadVO.class, new Integer(id));
return file;
}
{
// String query = "select * from trnimage where ID = ?";
FileuploadVO file = (FileuploadVO) template.getSessionFactory().openSession().load(FileuploadVO.class, new Integer(id));
return file;
}
}
SERVICE LAYER:
package org.fileupload.service;
import org.fileupload.model.FileuploadVO;
public interface fiileUploadService {
public void saveImage(FileuploadVO fileupload);
public FileuploadVO downloadImg(String id);
public FileuploadVO downloadImg(String id);
}
package org.fileupload.service;
import org.fileupload.dao.fileUploadDaoImpl;
import org.fileupload.model.FileuploadVO;
import org.springframework.beans.factory.annotation.Autowired;
public class fileUploadServiceImpl implements fiileUploadService{
@Autowired
private fileUploadDaoImpl fileuploadDAO;
@Override
public void saveImage(FileuploadVO fileupload) {
fileuploadDAO.saveImage(fileupload);
}
public FileuploadVO downloadImg(String id) {
return fileuploadDAO.downloadImg(id);
}
public FileuploadVO downloadImg(String id) {
return fileuploadDAO.downloadImg(id);
}
}
dbConfig.properties
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/studentdb
jdbc.username = root
jdbc.password = admin!@#
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>Optic Solution</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationcontext-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<servlet>
<servlet-name>applicationcontext</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>applicationcontext</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
applicationcontext-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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="org.fileupload.controller"></context:component-scan>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>classpath:resources/dbConfig.properties</value> </property>
</bean>
<!-- Hibernate Configuration -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>org.fileupload.model.FileuploadVO</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true </prop>
<prop key="hibernate.dbcp.initialSize">8</prop>
<prop key="hibernate.dbcp.maxActive">20</prop>
<prop key="hibernate.dbcp.maxIdle">20</prop>
<prop key="hibernate.dbcp.minIdle">0</prop>
<prop key="hibernate.hbm2ddl.auto">none</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<constructor-arg ref="mySessionFactory" />
</bean>
<!-- list of bean definations -->
<bean id="fileuploadDAO" class="org.fileupload.dao.fileUploadDaoImpl">
<constructor-arg ref="hibernateTemplate" />
</bean>
<bean id="fileuploadService" class="org.fileupload.service.fileUploadServiceImpl">
</bean>
<bean id="JsonMapper" class="org.optical.handler.JsonMapper"></bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="cacheSeconds" value="0" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242880" />
</bean>
</beans>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head><title>Upload and Download files using Spring</title></head>
<body>
<h2>Add New File</h2>
<%-- <form action="upload.htm" method="post" enctype="multipart/form-data">
<table width="60%" border="1" cellspacing="0">
<tr>
<td width="35%"><strong>File to upload</strong></td>
<td width="65%"><input type="file" name="file" /></td>
</tr>
<tr>
<td><strong>Notes</strong></td>
<td><input type="text" name="notes" width="60" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Add"/></td>
</tr>
</table>
</form> --%>
<form:form method="post" action="upload.htm"
modelAttribute="uploadForm" enctype="multipart/form-data">
<p>Select files to upload. Press Add button to add more file
inputs.</p>
<table id="fileTable">
<tr>
<td><input name="files[0]" type="file" /></td>
</tr>
<tr>
<td><input name="files[1]" type="file" /></td>
</tr>
</table>
<br />
<input type="submit" value="Upload" />
<input id="addFile" type="button" value="Add File" />
</form:form>
</body>
</html>
uploadfilesuccess.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" %>
<!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>
<p>Awesome.. Following file is uploaded successfully.</p>
<table width="80%" border="1" cellspacing="0" cellpadding="5">
<tr>
<th width="4%">No</th>
<th width="30%">Filename</th>
<th width="20%"> </th>
</tr>
<c:choose>
<c:when test="${files != null}">
<c:forEach var="file" items="${files}" varStatus="counter">
<tr>
<td>${counter.index + 1}</td>
<td>${file}</td>
<td><div align="center"><a href="download.htm?id=${ids}">Download</a> </div></td>
</td>
</tr>
</c:forEach>
</c:when>
</c:choose>
</table>
</body>
</html>
Screenshot of application is as given below:
Thanks for reading this article
for any query ping me on pathak.nisarg@yahoo.com
No comments:
Post a Comment