Saturday, October 9, 2010

Form based File Upload in HTML


Upload File
In this blog, we will learn how to upload a file at server machine from client machine using Web Application


A Brief Idea
 
We will use Apache Commons FileUpload APIs to implement our upload file application.
Here, we need two APIs namely:
  1. commons-fileupload-1.2.1.jar
  2. commons-io-1.3.2.jar
FileUpload depends on Commons IO, so make sure you have the version mentioned on the dependencies page in your classpath before continuing. 
You can download these APIs from Apache website,Click here


Here We Go







I am going to write a jsp page as a client. My jsp file name is index.jsp.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>Upload File Example</title>
  </head>
  <body>
    <FORM name="filesForm" method="post" enctype="multipart/form-data"
      action="./UploadFileController">
         <input type="file" name="filePath" id="filePath" size="20px"/>
         <input type="submit" value="Import">
    </FORM>
  </body>
</html>

  • In the form tag, I am using enctype="multipart/form-data". The "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.For more details about content type, Click here 
  • action="./UploadFileController" is the servlet's url-pattern defined in web.xml.
  • <input type="file" /> This control type llows the user to select files so that their contents may be submitted with a form. The INPUT element is used to create a file select control.


Here is our servlet definition.The name of the servlet is UploadFileController.java

package com.sarf.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sarf.business.UploadFileToServer;

public class UploadFileController extends HttpServlet {
      private static final long serialVersionUID = 1L;
  
 public UploadFileController() {
 }
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
 }
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    //Class responsible for reading the request and uploading the file into server
    UploadFileToServer upload = new UploadFileToServer();
    //Calling the method uploadFile()
    String strFile = upload.uploadFile(request);
    System.out.println("File Upload Message"+strFile);
  }
 }

Here is the content of web.xml.
<?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>Upload Example</display-name>
      <servlet>
            <description></description>
            <display-name>UploadFileController</display-name>
            <servlet-name>UploadFileController</servlet-name>
            <servlet-class>com.sarf.controller.UploadFileController</servlet-class>
      </servlet>
      <servlet-mapping>
            <servlet-name>UploadFileController</servlet-name>
            <url-pattern>/UploadFileController</url-pattern>
      </servlet-mapping>
      <welcome-file-list>
            <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
</web-app>


Here is our  UploadFileToServer.java

package com.sarf.business;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFileToServer {
     
public String uploadFile(HttpServletRequest pRequest)
{
 File file = null;
 boolean isMultipart = false;
 List fileItems = null;
 Iterator itr = null;
 FileItem fileItem = null;

 try
 {
   // Check that we have a file upload request
   isMultipart = ServletFileUpload.isMultipartContent(pRequest);
   if(isMultipart)
   {
    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload fu= new ServletFileUpload(factory);
    // Parse the request
    fileItems = fu.parseRequest(pRequest);
    itr = fileItems.iterator();
    fileItem = (FileItem)itr.next();
   
    if(!fileItem.isFormField()) {
      file= new File("K:\\","uploadedFileName.txt");
      // Write file into disk
      fileItem.write(file);
      }
   }
  }catch(Exception e){
    //Handle your exception here 
    return "Your Failure Message Goes Here";
   }
  //Returning the uploaded file path
  return file.getAbsolutePath();
 }
}

You can upload multiple files using this program by modifying the code appropriately.In fileItems list, you can have more than one FileItem and get it using Iterator.

You can get the absolute file path using fileItem.getName() method and parse it to get file name.
In the following code snippet ' file= new File("K:\\","uploadedFileName.txt");',I used hard coded value for simplicity of my code. It is recommended to use the original uploaded file name in the above code.
"K:\\"  is the drive name on server.