Pages

Wednesday 4 September 2013

Handling file upload in java using servlet

In this post we will see how to handle file upload in java using servlet. File upload is one of the very extensively used functionality in any application. There are many ways how you can achieve this. However we will be focusing on how it can be achieved via java servlet.


So we will start by writing a Jsp page where user can browse any file from his machine and then click on Upload File button to  upload the file to the destination.

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>File upload form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadServlet" method="post"
                       enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>

</html>

So in the index.jsp file we could see we are calling UploadServlet and the action is post on the form submission. So lets now write our servlet class which will handle the upload functionality. We will be uploading the file to a location which is defined in web.xml as a parameter.

UploadServlet.java


import java.io.*;
import java.util.Iterator;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;

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

public class UploadServlet extends HttpServlet { 
    /**

*/
private static final long serialVersionUID = 1L;

public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException,IOException {
System.out.println("Starting to Upload the file...");
        File file ;
        int maxFileSize = 5000 * 1024;
        int maxMemSize = 5000 * 1024;
        ServletContext context = getServletContext();
        //Getting the upload location from web.xml
        String filePath = context.getInitParameter("file-upload");

        // Verify the content type
        String contentType = req.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {
        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(req);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        while ( i.hasNext () ) 
        {
        FileItem fi = (FileItem)i.next();
        if ( !fi.isFormField () )
        {
        // Get the uploaded file parameters
        String fieldName = fi.getFieldName();
        String fileName = fi.getName();
        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 ) ;
        System.out.println("Uploaded Filename: " + filePath +"\\"+fileName);
        }
        }
        }catch(Exception ex) {
        System.out.println(ex);
        }
        }
}
}


Add the UploadServlet mapping in web.xml and also the location where you want to upload the files to (Upload location). You can notice the file-upload parameter in the web.xml which corresponds to the upload location.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>FileUpload</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <context-param> 
    <description>Location to store uploaded file</description> 
    <param-name>file-upload</param-name> 
    <param-value>
         D:\apache-tomcat-6.0.35\webapps\data
     </param-value> 
 </context-param>

    <servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>

</web-app>

We need to add two jars also to our project that are commons-fileupload-1.2.2.jar and commons-io-2.4.jar. Now you are ready with the file upload functionality and should be able to get it working fine. I hope this post would have helped you.

No comments:

Post a Comment