Friday, January 22, 2010

Java Upload Servlet

This week I'm providing a simple example of a java servlet that can process uploaded files from a multi part web form post.

I'm using the FileUpload component provided by the Apache Commons project. I've tried a few other packages, but this appears to be the most straight forward technique I've found. Most of the heavy lifting has been abstracted for you by the Apache team.

The classes in use below are found in the commons-fileupload-X.X.X.jar (1.2.1 currently) library which can be downloaded from the FileUpload component page on the apache commons website. This library itself is dependent on the Apache Commons - IO component.

Here is the example Servlet:

package com.blogspot.codingitforward.servlets;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import java.util.List;

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

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

public class FileUploadServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
response.setContentType(CONTENT_TYPE);

//Simply getting the user's home directory so we have a place to write the files.
String sUserDir = System.getProperty("user.home") + System.getProperty("file.separator");

//Create a new instance of the file factory.
FileItemFactory factory = new DiskFileItemFactory();
//Initialize your file upload parser
ServletFileUpload upload = new ServletFileUpload(factory);

try {
//Parse the request, it returns a List, containing FileItem objects
List<FileItem> fileItems = upload.parseRequest(request);

//process the files
for (FileItem fileItem: fileItems) {
//This is a simple way to save them to disk, but you
//could also just process the files by getting the input stream right
//from FileItem
File persistedFile = new File(sUserDir + fileItem.getName());
fileItem.write(persistedFile);

out.println("
Recieved file: " + fileItem.getName());
out.println("Size: " + fileItem.getSize());
out.println("Saved To: " + persistedFile.getPath() + "\n
");
}
} catch (FileUploadException fileEx) {
fileEx.printStackTrace();
throw new ServletException("Error parsing uploaded files", fileEx);
} catch (Exception ex) {
ex.printStackTrace();
throw new ServletException("Error saving files on server", ex);
}
}
}


In order to test this servlet I created a simple HTML form to post the files:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

  <head>

    <title>uploadFile</title>

  </head>

  <body>

<form action="fileUploadServlet" method="post" enctype="multipart/form-data">

      

  <p>

  Upload File 1: <input type="file" name="fileTest"/><br/>

  Upload File 2: <input type="file" name="fileTest"/>

  <p>

  <input type="submit" />

    </form>  

  </body>

</html>


In my next blog entry, I'll be creating a process using a java client to push files using libraries from the latest HttpClient package - a project that has branched off from the apache commons project.