Posted In: Spring MVC

Spring3 File Upload example

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
  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_4.xsd">
  <display-name>SpringApp</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  <context-param>
    <description>spring context configuration</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/springapp-servlet.xml</param-value>
  </context-param>
  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>springapp</param-value>
  </context-param>

  <context-param>
    <description>
      log4j configuration used by Log4jConfigListener
    </description>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/classes/log4j.xml</param-value>
  </context-param>
  <context-param>
    <description>
      log4j configuration used by Log4jConfigListener
    </description>
    <param-name>log4jRefreshInterval</param-name>
    <param-value>1000</param-value>
  </context-param>
  <listener>
    <!-- Bootstrap listener for custom log4j initialization in a web environment -->
    <listener-class>
      org.springframework.web.util.Log4jConfigListener
    </listener-class>
  </listener>

  <listener>
    <!-- Bootstrap listener to start up Spring's root WebApplicationContext. -->
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>

  <servlet>
    <display-name>springapp</display-name>
    <servlet-name>springapp</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>/upload/form</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>/upload/save</url-pattern>
  </servlet-mapping>
</web-app>
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<context:component-scan base-package="com.company.springapp"/>
	
	<bean id="messages"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="message" />
	</bean>
	<alias name="messages" alias="messageSource" />

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

	<bean id="uploadController"
		class="com.company.springapp.UploadController">
		<property name="uploadFolderPath">
			<value>${docs.upload.folder}</value>
		</property>
	</bean>

	<bean id="prop-config"
	  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:fileupload.DEV.properties</value>
			</list>
		</property>
	</bean>

	<bean id="multipartResolver"
	  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- one of the properties available; the maximum file size in bytes -->
		<property name="maxUploadSize" value="52428800 " />
	</bean>
</beans>
package com.company.springapp;

import java.io.Serializable;

import org.springframework.web.multipart.MultipartFile;

public class UploadCommand implements Serializable
{
  private MultipartFile document1;
  private MultipartFile document2;
  private MultipartFile document3;
  private MultipartFile document4;

  public MultipartFile getDocument1() {
    return document1;
  }

  public void setDocument1(MultipartFile document1) {
    this.document1 = document1;
  }

  public MultipartFile getDocument2() {
    return document2;
  }

  public void setDocument2(MultipartFile document2) {
    this.document2 = document2;
  }

  public MultipartFile getDocument3() {
    return document3;
  }

  public void setDocument3(MultipartFile document3) {
    this.document3 = document3;
  }

  public MultipartFile getDocument4() {
    return document4;
  }

  public void setDocument4(MultipartFile document4) {
    this.document4 = document4;
  }
}
package com.company.springapp;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/upload")
public class UploadController {
	private static final Logger logger = Logger
			.getLogger(UploadController.class);

	private String uploadFolderPath;

	public String getUploadFolderPath() {
		return uploadFolderPath;
	}

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

	@RequestMapping(value = "/form")
	protected ModelAndView loginformHandler(@ModelAttribute("command")
	UploadCommand command) throws Exception {
		logger.info("start");
		ModelAndView mav = new ModelAndView();
		try {
			mav.setViewName("upload");
			mav.addObject(command);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}

	@RequestMapping(value = "/save")
	protected ModelAndView saveHandler(@ModelAttribute("command")
	UploadCommand command) throws Exception {
		logger.info("start::" + BeanUtils.describe(command));
		ModelAndView mav = new ModelAndView();
		try {
			writeFile((UploadCommand) command);
			mav.setViewName("uploadSuccess");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}

	private void writeFile(UploadCommand bean) throws Exception {
		String filePath = getUploadFolderPath() + getDateyyyyMMdd_HHmmssSS();

		try {
			logger.info("Start file write");
			if (bean.getDocument1() != null
					&& bean.getDocument1().getSize() > 0) {
				bean.getDocument1().transferTo(
						new File(filePath
								+ "_1"
								+ getFileExt(bean.getDocument1()
										.getOriginalFilename())));
			}
			if (bean.getDocument2() != null
					&& bean.getDocument2().getSize() > 0) {
				bean.getDocument2().transferTo(
						new File(filePath
								+ "_2"
								+ getFileExt(bean.getDocument2()
										.getOriginalFilename())));
			}
			if (bean.getDocument3() != null
					&& bean.getDocument3().getSize() > 0) {
				bean.getDocument3().transferTo(
						new File(filePath
								+ "_3"
								+ getFileExt(bean.getDocument3()
										.getOriginalFilename())));
			}
			if (bean.getDocument4() != null
					&& bean.getDocument4().getSize() > 0) {
				bean.getDocument4().transferTo(
						new File(filePath
								+ "_4"
								+ getFileExt(bean.getDocument4()
										.getOriginalFilename())));
			}
			logger.info("End file write");
		} catch (Exception e) {
			logger.error(e, e);
		}
	}

	private static String getDateyyyyMMdd_HHmmssSS() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmssSS");
		return sdf.format(new Date(System.currentTimeMillis()));
	}

	private static String getFileExt(String filePath) {
		return filePath.substring(filePath.lastIndexOf("."), filePath.length());
	}
}
<%
String ctx = request.getContextPath();
%>
<html>
<head>
<title>/WEB-INF/jsp/upload.jsp</title>
</head>

<body>
<form name="uploadDocs" method="post" action="<%=ctx%>/upload/save"
	enctype="multipart/form-data">
<table width="100%" border="0" cellpadding="0" cellspacing="0"
	bgcolor="#FFFFFF">
	<tr>
		<td><input type="file" value="Upload Docs1" name="document1" />
		</td>
	</tr>
	<tr>
		<td><input type="file" value="Upload Docs2" name="document2" />
		</td>
	</tr>
	<tr>
		<td><input type="file" value="Upload Docs3" name="document3" />
		</td>
	</tr>
	<tr>
		<td><input type="file" value="Upload Docs4" name="document4" />
		</td>
	</tr>
	<tr>
		<td><input type="submit" value="UploadDocs" name="uploaddocs" />
		</td>
	</tr>
</table>
</form>
</body>
</html>
<%
String ctx = request.getContextPath();
%>
<html>
<head>
<title>/WEB-INF/jsp/uploadSuccess.jsp</title>
</head>

<body onload="">

<form name="upload" method="post" action="upload">
<table width="100%" border="0" cellpadding="0" cellspacing="0"
	bgcolor="#FFFFFF">
	<tr>
		<td>Upload Successful</td>
	</tr>
</table>
</form>
</body>
</html>

Tags: ,

by , on January 14th, 2017

  • Categories