Servlet Pdf File Upload Project

Click here to download eclipse supported ZIP file




 

    
package com.cv.servlet.pdf.upload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

/**
 * Servlet implementation class PdfFileUploadHandler
 
 @author Chandra Vardhan
 
 */

public class PdfFileUploadHandler extends HttpServlet {

  private static final Logger LOGGER = Logger.getLogger(PdfFileUploadHandler.class);
  private static String storagePath = null;

  /**
   @see HttpServlet#HttpServlet()
   */
  public PdfFileUploadHandler() {
    super();
  }

  @Override
  public void init() throws ServletException {
    // process only if its multipart content
    File file = new File("C:\\pdf_files");
    if (!file.exists()) {
      file.mkdir();
      storagePath = file.getPath()+"\\";
      LOGGER.info("LOGGER : Folder has been created successfully : " + storagePath);
    else {
      storagePath = file.getPath()+"\\";
      LOGGER.info("LOGGER : Folder already exist : " + storagePath);
    }

  }

  /**
   @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    LOGGER.info(
        "LOGGER : Entered into doGet(HttpServletRequest ,HttpServletResponse ) of PdfFileUploadHandler class... ");

    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    if (ServletFileUpload.isMultipartContent(request)) {
      try {
        List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

        for (FileItem item : multiparts) {
          if (!item.isFormField()) {
            String name = new File(item.getName()).getName();
            
            LOGGER.error("File name is : : "+ name);
            // This line is used to write the uploaded file to
            // working folder
            item.write(new File(storagePath + name));

          }
        }
        // File uploaded successfully
      catch (Exception ex) {
        LOGGER.error("File Upload Failed due to " + ex);
        out.print("<br><br><font color='RED'><center>File Upload Failed... </center></font>");
      }

    else {
      LOGGER.error("Sorry this Servlet only handles file upload request");
      out.print("<br><br><font color='RED'><center>Sorry this Servlet only handles file upload request</center></font>");
    }
    out.print("<br><br><font color='GREEN'><center>File Uploaded Successfully  @ : " + storagePath+"</center></font>");

    LOGGER.info("LOGGER : File Uploaded Successfully  @ : " + storagePath);
  }

  /**
   @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOGGER.info(
        "LOGGER : Entered into doPost(HttpServletRequest ,HttpServletResponse ) of PdfFileUploadHandler class... ");

    doGet(request, response);
  }

}



<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Pdf Upload</title>
</head>
<body>
<br><br>
<form action="PdfFileUploadHandler" method="post" enctype="multipart/form-data">
<table align="center">
<tr >
<td><input type="file" name="file" /></td>
</tr>
<tr>
<td align="right"><input type="submit" value="upload" /></td>
</tr>
</table>
</form>
</body>
</html>



#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




<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"> <modelVersion>4.0.0</modelVersion> <artifactId>ServletPdfFileUpload</artifactId> <version>1.0</version> <packaging>war</packaging> <properties> <log4j.version>1.2.16</log4j.version> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies> <groupId>com.pdf.upload</groupId> </project>




 
<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>PdfFileUploadHandler</servlet-name> <servlet-class>com.cv.servlet.pdf.upload.PdfFileUploadHandler</servlet-class> </servlet> <servlet-mapping> <servlet-name>PdfFileUploadHandler</servlet-name> <url-pattern>/PdfFileUploadHandler</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>uploadfile.jsp</welcome-file> </welcome-file-list> </web-app>


No comments:

Post a Comment