Upload File using Servlet


To send an email using your a Servlet is simple enough but to start with you should have commons-fileupload.x.x.jar and commons-io-x.x.jar library files in your class path directory.

You Can download this files from You can download it from
commons-fileupload.x.x.jar ==>http://commons.apache.org/fileupload/
commons-io-x.x.jar ==> http://commons.apache.org/io/.

Upload.html

<html><head>
<title>File Uploading Form</title>
</head><body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="Upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" /><br />
<input type="submit" value="Upload File" />
</form>
</body></html>

web.xml

Add following lines in web.xml. This would take care of accepting uploaded file and to store it in directory c:\uploaded\.

<context-param>
    <description>Location to store uploaded file</description>
    <param-name>file-upload</param-name>
    <param-value>c:\uploaded\</param-value>
</context-param>

Upload.Java

// Import required java libraries
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;

public class Upload extends HttpServlet {
  
   private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;

   public void init( ){
      // Get the file location where it would be stored.
      filePath =
             getServletContext().getInitParameter("file-upload");
   }
   public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
  // Check that we have a file upload request
  isMultipart = ServletFileUpload.isMultipartContent(request);
  response.setContentType("text/html");
  java.io.PrintWriter out = response.getWriter( );
  if( !isMultipart ){
     out.println("<html><head>");
     out.println("<title>Servlet upload</title>"); 
     out.println("</head><body>");
     out.println("<p>No file uploaded</p>");
     out.println("</body></html>");

     return;
  }
  DiskFileItemFactory factory = new DiskFileItemFactory();
  // maximum size that will be stored in memory
  factory.setSizeThreshold(maxMemSize);
  // Location to save data that is larger than maxMemSize.
  factory.setRepository(new File("c:\\temp"));

  // Create a new file upload handler
  ServletFileUpload upload = new ServletFileUpload(factory);
  // maximum file size to be uploaded.
  upload.setSizeMax( maxFileSize );
  try{
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);
   
      // Process the uploaded file items
      Iterator i = fileItems.iterator();
      out.println("<html><head>");
      out.println("<title>Servlet upload</title>");
      out.println("</head><body>");

      while ( i.hasNext () )
      {
         FileItem fi = (FileItem)i.next();
         if ( !fi.isFormField () )   
         {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            String contentType = fi.getContentType();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
               file = new File( filePath +
               fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
               file = new File( filePath +
               fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
            out.println("Uploaded File: " + fileName + "<br>");
         }
      }
      out.println("</body>");
      out.println("</html>");
   } catch(Exception ex) { System.out.println(ex);  }
   }
}


Output

Upload.html
Upload Servlet

0 comments :