Basic File Upload with Apache Commons

31 Mar

Below is the piece of servlet code which you are try out in case if you even has a requirement for implementing a basic uploads in your website with Apache Commons File Upload library.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package test;

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

import javax.servlet.ServletConfig;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

public class UploadPDF extends HttpServlet {

    private static final String TMP_DIR_PATH = “D:\\temp”;
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = “D:\\UploadedPDF”;
    private File destinationDir;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        tmpDir = new File(TMP_DIR_PATH);
        if (!tmpDir.isDirectory()) {
            throw new ServletException(TMP_DIR_PATH + ” is not a directory”);
        }
        String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(DESTINATION_DIR_PATH);
        if (!destinationDir.isDirectory()) {
            throw new ServletException(DESTINATION_DIR_PATH + ” is not a directory”);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        response.setContentType(“text/plain”);

        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        /*
         *Set the size threshold, above which content will be stored on disk.
         */
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
        /*
         * Set the temporary directory to store the uploaded files of size above threshold.
         */
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

        try {
            /*
             * Parse the request
             */
            List items = uploadHandler.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                /*
                 * Handle Form Fields.
                 */
                String fileName = item.getName();

                if (item.isFormField()) {
                    out.println(“File Name = ” + item.getFieldName() + “, Value = ” + item.getString());
                } else {
                    //Handle Uploaded files.
                    out.println(“Field Name = ” + item.getFieldName()
                            + “, File Name = ” + item.getName()
                            + “, Content type = ” + item.getContentType()
                            + “, File Size = ” + item.getSize()
                            + “, boolean isInMemory = ” + item.isInMemory());
                    /*
                     * Write file to the location.
                     */

                    out.println(“File Name is = ” + FilenameUtils.getName(fileName));
                    File file = new File(destinationDir, FilenameUtils.getName(fileName));
                    out.println(destinationDir);
                    out.println(item.getName());                 
                    item.write(file);
                }
                out.close();
            }
        } catch (FileUploadException ex) {
            log(“Error encountered while parsing the request”, ex);
        } catch (Exception ex) {
            log(“Error encountered while uploading file”, ex);
        }

    }
}

Please make sure that you have apache commons IO library in your container lib folder or common io jar files in your application lib folder.In addition to commons IO library you will also need to download file upload jar files and place them in webapps lib folder.All these jars are the must for this code to run.More details on the location of these files can be found here.

In addition to having all the dependencies imported to your project,you also have make sure that proper encoding method is set in your form’s page that is request encoding type should be set as

enctype=”multipart/form-data”

In addition to this we also need to ensure that filename/file size/content is properly send by the client(browsers).Sometimes it might happen that due to some security policies, all these information might be blocked so I suggest to check for these possibilities in case if you find any issues.We can check this by giving couple of print statements and making sure that none of the values are coming out as null.

At the time of writing this post, I have checked that this code works with IE9/FF10/Safari5.03/Opera 10x.

Technorati Tags: ,
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: