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.

Wednesday, December 23, 2009

Forward

Coding it forward. In other words, I'm here to share what I've likely learned from others in this world of ones and zeros. I often find myself scouring the internet for solutions to problems that seem very complicated, but in the end the solution usually turns out to be very simple and straight forward.

This is of course after much frustration, lots of coffee, temper tantrums, and sometimes cursing which has probably caused my coworkers enough concern to arm themselves in preparation for cubicle defense. The solution is usually arrived at by assembling bits and pieces from several sources until it all becomes clear. Other times, it is just a matter of wading through thousands of bad solutions until the cleanest one is found.

Sometimes it even makes sense. Sometimes I don't understand it completely, but I do know that it works.

I like solving problems; it is why I'm in the IT field, just like many of you probably are. If you don't find the solution you're looking for feel free to ask me - post a question, make me work for your interest. Most of my posts will revolve around solutions in Java, JBoss, MySQL, Oracle, and Linux. These are the tools I'm currently the most active in, but I have a diverse exposure to many other technologies, such as ASP.NET, C#, perl, PHP, VB, PowerBuilder, etc... the list goes on.

So, my goal with this blog is to assemble these nuggets of genius (okay, I'm using that term very loosely), and "pay it forward", by presenting them for any of you frustrated geeks out there seeking answers with the infamous google search engine hoping to find those magic keywords that throw the solution back at you.

To christen this blog, I'm going to start it with a simple classic algorithm for randomizing a collection. I like to refer to it as the "shuffle" algorithm. I'll be doing the "HOW TO" example in Java, but you could easily transfer this same technique to any language. If you'd like it presented in another language feel free to post a comment, and if I'm capable I'll try to provide an example.


package com.blogspot.codingitforward;

import java.util.Random;

public class ShuffleExample {
public ShuffleExample() {
//Creating a sample int array
int[] shuffledArray = new int[100];

//setting up some values to randomize
for(int ndx = 0; ndx < shuffledArray.length; ndx++) {
shuffledArray[ndx] = ndx + 1;
}

//Initialize your random number generator
Random random = new Random();

//loop through the array, and "shuffle" the items by swapping them.
//some items will be swapped several times, but you can be assurred that
//every element will be moved at least once. This allows you to very efficiently
//randomize a set, and also keep the set finite.
for(int ndx = 0; ndx < shuffledArray.length; ndx++) {
//grab a random number between 0, and the size of your collection
int iRand = random.nextInt(shuffledArray.length);

//put the current value in a temporary holder
int iTemp = shuffledArray[ndx];

//set the value for your current index value to the random element
shuffledArray[ndx] = shuffledArray[iRand];

//set the value for the random element to what WAS the current one
shuffledArray[iRand] = iTemp;
}

//For grins, lets output the random results
for(int ndx = 0; ndx < shuffledArray.length; ndx++) {
System.out.println("Element " + ndx + " = " + shuffledArray[ndx]);
}
}

public static void main(String[] args) {
ShuffleExample shuffleExample = new ShuffleExample();
}
}


Stay tuned. I may provide an extended example which utilizes this technique to update database records with random values.

I know, it is quite riveting. I bet you're on the edge of your seat right now.