Spring4 MVC File Upload Project

Click here to download eclipse supported ZIP file



This is upload.jsp JSP file and it is used display the output for the application.



<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="false"%>
<html>
<head>
<title>Upload File Request Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="<c:url value='/static/css/bootstrap.css' />"
rel="stylesheet"></link>
<link href="<c:url value='/static/css/app.css' />" rel="stylesheet"></link>
<link rel="stylesheet" type="text/css"
href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css" />
</head>
<body>
<div id="mainWrapper">
<div class="login-container">
<div class="login-card">
<h3 align="center">
<a href="uploadMultiple.jsp">click here to test multiple files</a>
</h3>
<div class="login-form">
<form method="POST" action="uploadFile"
enctype="multipart/form-data" class="form-horizontal">
<div class="input-group input-sm">
<label for="Upload File"><h4>Select a file to upload!!!</h4></label><input
type="file" class="form-control" id="file" name="file"
placeholder="Select file to upload" required />
</div>
<br>
<div class="form-actions">
<input type="submit"
class="btn btn-block btn-primary btn-default"
value="Upload File">
</div>
</form>
</div>
</div>
</div>
</div>
<br>
</body>
</html>


This is uploadMultiple.jsp JSP file and it is used display the output for the application.



<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Upload Multiple File Request Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="<c:url value='/static/css/bootstrap.css' />"
rel="stylesheet"></link>
<link href="<c:url value='/static/css/app.css' />" rel="stylesheet"></link>
<link rel="stylesheet" type="text/css"
href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css" />
</head>
<body>
<div id="mainWrapper">
<div class="login-container">
<div class="login-card">
<div class="login-form">
<form method="POST" action="uploadMultipleFile"
enctype="multipart/form-data" class="form-horizontal">
<div class="input-group input-sm">
<label for="Upload File">Select multiple file(s) to upload!!!</label><input
type="file" class="form-control" id="file" name="file"
placeholder="Select file to upload" required />
</div>
<br>
<div class="input-group input-sm">
<label for="Upload File"></label><input
type="file" class="form-control" id="file" name="file"
placeholder="Select file to upload" required />
</div>
<br>
<div class="form-actions">
<input type="submit"
class="btn btn-block btn-primary btn-default"
value="Upload File">
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>


This is failure.jsp JSP file and it is used display the output for the application.



<%@ 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" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Failure Page</title>
</head>
<body>
<br>
<br>
<h3 align="center">
<font color="RED">Failed to upload file to the
destination!!!</font>
</h3>
</body>
</html>


This is success.jsp JSP file and it is used display the output for the application.



<%@ 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"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success Page</title>
</head>
<body>
<br>
<br>
<h3 align="center">
<font color="Green">File uploaded successfully to the
destination!!!</font>
</h3>
</body>
</html>



This is FileUploadController.java file having the controller logic and it will have the services defined in it.


 

    
package com.cv.spring.fileupload;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * Handles requests for the application file upload requests 
 
 @author Chandra Vardhan
 *
 */

@Controller
public class FileUploadController {

  private static final Logger LOGGER = LoggerFactory
      .getLogger(FileUploadController.class);

  /**
   * Upload single file using Spring Controller
   */
  @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
  public String uploadFileHandler(@RequestParam("file"MultipartFile file) {
    
    LOGGER.info("IN FileUploadController.uploadFileHandler(- -)");

    String name = file.getOriginalFilename();
    LOGGER.info("The uploading file name  : : "+ name);
    if (!file.isEmpty()) {
      try {
        byte[] bytes = file.getBytes();

        // Creating the directory to store file
        String rootPath = System.getProperty("catalina.home");
        LOGGER.info("Context path : : "+ rootPath);
        File dir = new File(rootPath + File.separator + "tmpFiles");
        if (!dir.exists())
          dir.mkdirs();
        
        // Create the file on server
        File serverFile = new File(dir.getAbsolutePath()
            + File.separator + name);
        LOGGER.info("The uploading file path  : : "+ serverFile.getName());
        BufferedOutputStream stream = new BufferedOutputStream(
            new FileOutputStream(serverFile));
        stream.write(bytes);
        stream.close();

        LOGGER.info("Server File Location : : "
            + serverFile.getAbsolutePath());
        LOGGER.info("You successfully uploaded file : : " + name);
        return "success";
      catch (Exception e) {
        LOGGER.error("You failed to upload " + name + " => " + e.getMessage());
        return "failure";
      }
    else {
      LOGGER.error("You failed to upload " + name
          " because the file was empty.");
      return "failure";
    }
  }

  /**
   * Upload multiple file using Spring Controller
   */
  @RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
  public @ResponseBody String uploadMultipleFileHandler(@RequestParam("file"MultipartFile[] files) {

    LOGGER.info("IN FileUploadController.uploadMultipleFileHandler(- -)");

    String message = "";
    for (int i = 0; i < files.length; i++) {
      MultipartFile file = files[i];
      String name = file.getOriginalFilename();
      LOGGER.info("The uploading file name  : : "+ name);
      try {
        byte[] bytes = file.getBytes();

        // Creating the directory to store file
        String rootPath = System.getProperty("catalina.home");
        File dir = new File(rootPath + File.separator + "tmpFiles");
        if (!dir.exists())
          dir.mkdirs();

        // Create the file on server
        File serverFile = new File(dir.getAbsolutePath()
            + File.separator + name);
        BufferedOutputStream stream = new BufferedOutputStream(
            new FileOutputStream(serverFile));
        stream.write(bytes);
        stream.close();

        LOGGER.info("Server File Location="
            + serverFile.getAbsolutePath());

        message = message + "You successfully uploaded file=" + name
            "<br />";
      catch (Exception e) {
        return "You failed to upload " + name + " => " + e.getMessage();
      }
    }
    return message;
  }
}




This is pom.xml file having the entries of dependency jars and information to build the application .


	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">.0" encoding="UTF-8"?> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.spring.fileupload</groupId> <artifactId>Spring4MVCFileUpload</artifactId> <name>Spring4MVCFileUpload</name> <packaging>war</packaging> <version>1.0</version> <properties> <java-version>1.8</java-version> <org.springframework-version>4.2.0.RELEASE</org.springframework-version> <org.aspectj-version>1.6.10</org.aspectj-version> <org.slf4j-version>1.6.6</org.slf4j-version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${org.aspectj-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${org.slf4j-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${org.slf4j-version}</version> runtime </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${org.slf4j-version}</version> runtime </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <groupId>javax.jms</groupId> <artifactId>jms</artifactId> <groupId>com.sun.jdmk</groupId> <artifactId>jmxtools</artifactId> <groupId>com.sun.jmx</groupId> <artifactId>jmxri</artifactId> runtime </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> provided </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> provided </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> test </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <warName>Spring4MVCFileUpload</warName> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project>


This is servlet-context.xml file having the spring configuration properties.


 
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/**" location="/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<beans:property name="maxUploadSize" value="100000" />
</beans:bean>

<context:component-scan base-package="com.cv.spring.fileupload" />

</beans:beans>


This is root-context.xml file having the spring configuration properties.


 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- Root Context: defines shared resources visible to all other web components -->

</beans>



This is web.xml deployment descriptor file and it describes how the web application should be deployed.


	
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>upload.jsp</welcome-file>
</welcome-file-list>
</web-app>



This is log4j.properties file having the entries for logging the information into the console/file.



#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


No comments:

Post a Comment