View RSS Feed

Servlet

How to write a Servlet that uploads file to server

Rate this Entry
by , 12-10-2011 at 04:19 AM (15487 Views)
Uploading files is a common operation for internet applications. Doing so in Java is pretty simple. This article will guide you through some steps to write a Java servlet that uploads a file then store it on the server.
Before going on, this article assumes that you have some Java web development experience, you are be able to use Eclipse IDE to write the code and deploy a web application on Tomcat 6.0 server.
The web application we are going to build contains the following components:

  • A servlet class, UploadServlet, that receives the data uploaded from client and save it into a file.
  • Two JSP pages, upload.jsp and done.jsp. The former page displays an interface that allows users to pick up a file from their computer to upload. The latter shows a message that indicates the upload has been succeeded.
  • The web deployment descriptor file, web.xml, which simply declares the servlet’s configuration.


Required libraries for upload file

We will use Apache Common File Upload to handle file upload. Download the library from http://commons.apache.org/fileupload...fileupload.cgi, the latest version is 1.2.2. This library depends on Apache Common IO library, so you also need to download it from http://commons.apache.org/io/download_io.cgi, the latest version is 2.1.
Import both of these JAR files, commons-fileupload-1.2.2.jar and commons-io-2.0.1.jar, into your project.

Writing the Servlet Class

The source code for the servlet is as follow, some comments are added to explain the code:


Java Code: The servlet class
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

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

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;

public class UploadServlet extends javax.servlet.http.HttpServlet implements
        javax.servlet.Servlet {
    static final long serialVersionUID = 1L;

    private static final String DATA_DIRECTORY = "data";
    private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
    private static final int MAX_REQUEST_SIZE = 1024 * 1024;

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (!isMultipart) {
            return;
        }

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Sets the size threshold beyond which files are written directly to disk.
        factory.setSizeThreshold(MAX_MEMORY_SIZE);

        // Sets the directory used to temporarily store files that are larger
        // than the configured size threshold. We use temporary directory for java
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
       
        // constructs the folder where uploaded file will be stored
        String uploadFolder = getServletContext().getRealPath("")
                                    + File.separator + DATA_DIRECTORY;

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);
       
        try {
            // Parse the request
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadFolder + File.separator + fileName;
                    File uploadedFile = new File(filePath);
                   
                    // saves the file to upload directory
                    item.write(uploadedFile);
                }
            }
           
            // displays done.jsp page after upload finished
            getServletContext().getRequestDispatcher("/done.jsp").forward(request, response);
           
        } catch (FileUploadException ex) {
            throw new ServletException(ex);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }       
    }
}


Note that we implement only doPost() method in the servlet . Something you need to pay attention is:

  • The constant DATA_DIRECTORY specifies the directory where files are stored. The directory is relative to the web application’s directory, and its absolute path is constructed as per the following line:


    Java Code:
            String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

  • The constant MAX_MEMORY_SIZE specifies the maximum memory (in bytes) that data will be stored temporarily, in case the data is greater than this threshold, the data will be stored directly on disk.
  • The constant MAX_REQUEST_SIZE specifies the maximum size (in bytes) of data in the HTTP request (including both multi-part form data and other POST parameters). If a request conveys data that is bigger than this limit, the server will throw an exception.


It is important to check if the request’s form content type is multi-part/form-data as follow:


Java Code: Checking request's form content type
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            return;
        }


Because if a file is uploaded along with the request, the form content type will be multi-part/form-data.

On the client side, user will submit a form that contains file data via HTTP POST method. After the file is written to a directory on the server, the servlet will redirect user to a JSP page to inform the user that the upload has been done.

The above servlet will store files under a folder named “data” which is under web application folder. So make sure you create that folder before deploying the application.

Writing JSP Pages

First, we create a JSP page that allows user to select a file to upload. We name the file as “upload.jsp”, it looks like the following:


XML Code: The JSP file upload.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</title>
</head>
<body>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="dataFile" id="fileChooser"/><br/><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>


The page has a pretty simple form with a text field, a Browse button that allows users to select a file on their computer, and a Submit button.
Second, we create a result JSP page which is displayed after upload has been finished. We name it as “done.jsp”, its content looks like the following:


XML Code: The JSP file done.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 Done</title>
</head>
<body>
<h3>Your file has been uploaded!</h3>
</body>
</html>


It’s very simple, just display a message “Your file has been uploaded!”.

Configure the web.xml

You should map the UploadServlet class to handle the request specified in the form’s action property of the upload.jsp page. If you create the servlet by an IDE, such as Eclipse, the web.xml file is updated automatically. The web.xml for our application should look like the following:


XML Code: Content of the web deployment descriptor file
<?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>CodeWeb</display-name>
    <servlet>
        <description></description>
        <display-name>UploadServlet</display-name>
        <servlet-name>UploadServlet</servlet-name>
        <servlet-class>com.hainasoft.web.UploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UploadServlet</servlet-name>
        <url-pattern>/UploadServlet</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>upload.jsp</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>


Deploy and run the application

Now package our web application as a WAR file and deploy it to a web container, such as Apache Tomcat. This is quite simple if you are using an IDE like Eclipse.
After the server is started, type the following URL in your browser’s address bar:
http://localhost/UploadApp/upload.jsp
where UploadApp is our web application’s name. You may have a different name so make sure to type it correctly. The upload page should look like this:

Name:  screenshot1.PNG
Views: 6162
Size:  64.9 KB
Figure: The upload page

Click Browse button and select a file, then press Upload. A new page will be displayed indicating the upload has been done, like the following screen shot:

Name:  screenshot2.PNG
Views: 6088
Size:  64.9 KB
Figure: The result page

Check the upload folder on the server to make sure the file has been saved there.

Submit "How to write a Servlet that uploads file to server" to Facebook Submit "How to write a Servlet that uploads file to server" to Digg Submit "How to write a Servlet that uploads file to server" to del.icio.us Submit "How to write a Servlet that uploads file to server" to StumbleUpon Submit "How to write a Servlet that uploads file to server" to Google

Tags: file, servlet, upload Add / Edit Tags
Categories
Servlet , File

Comments