Posted In: Spring MVC

Spring2 simple file upload

<?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>FileUpload</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <context-param>
    <description>spring context configuration</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/fileupload-servlet.xml</param-value>
  </context-param>
  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>fileupload</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 to start up Spring's root WebApplicationContext. -->
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
  <listener>
    <!-- Bootstrap listener for custom log4j initialization in a web environment -->
    <listener-class>
      org.springframework.web.util.Log4jConfigListener
    </listener-class>
  </listener>

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

  <servlet-mapping>
    <servlet-name>fileupload</servlet-name>
    <url-pattern>/Upload</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:aop="http://www.springframework.org/schema/aop"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

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

<!--
	contains message resource bundle to support dynamic message templates.
	alias is added for due to autowiring spring's internal beans.
-->
<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="exception-resolver"
  class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
	<property name="exceptionMappings">
		<props>
			<prop key="java.lang.Exception">ErrorPage</prop>
		</props>
	</property>
</bean>

<!-- the application context definition for the springapp DispatcherServlet -->
<bean id="url-mapping"
  class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
	<property name="mappings">
		<map key-type="java.lang.String"
			value-type="java.lang.String">
			<entry key="/Upload" value-ref="uploadController" />
		</map>
	</property>
</bean>


<!-- .................................................................. -->
<!-- controller layer -->
<!-- .................................................................. -->

<!-- base config. for all controller beans, which should be subclass of SimpleFormController -->
<bean id="uploadController"
	class="com.company.fileupload.UploadController">
	<property name="supportedMethods" value="GET,POST" />
	<property name="requireSession" value="false" />
	<property name="useCacheControlHeader" value="true" />
	<property name="useCacheControlNoStore" value="true" />
	<property name="useExpiresHeader" value="true" />
	<property name="commandClass"
		value="com.company.fileupload.UploadCommand" />
	<property name="formView" value="upload" />
	<property name="successView" value="uploadSuccess" />
	<property name="uploadFolderPath">
		<value>${docs.upload.folder}</value>
	</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.fileupload;

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.fileupload;

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

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

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class UploadController extends SimpleFormController
{
  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;
  }

  protected ModelAndView processFormSubmission(HttpServletRequest request,
      HttpServletResponse response, Object command, BindException errors)
      throws Exception {
    logger.info(BeanUtils.describe(command));
    ModelAndView mav = null;
    try
    {
      mav = super.processFormSubmission(request, response, command, errors);
    }
    catch (Exception e)
    {
      logger.error(e, e);
    }
    return mav;
  }

  protected ModelAndView onSubmit(HttpServletRequest request,
      HttpServletResponse response, Object command, BindException errors)
      throws Exception {
    logger.info(BeanUtils.describe(command));
    writeFile((UploadCommand) command);
    return new ModelAndView(getSuccessView());
  }

   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 onload="">

<form name="uploadDocs" method="post" action="<%=ctx%>/Upload"
	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>

Tags: ,

by , on January 14th, 2017

  • Categories