Categories
Java

Servlets and submitting form using the POST method with enctype “multipart/form-data”

Uploading files from forms into a servlet appears to be a common sore in J2EE that was left to be addressed by developers. Apache has what appears to be a solid package in their org.apache.commons.fileupload package (get it here).

What is not clear (or if you merely forgot) is that when you use the form encoding (which you basically must when you are uploading a file) multipart/form-data is that the HttpServletRequest object will no longer hold the parameters from the form. You must use the a mechanism I found to be non-intuitive (if for the class names used if not anything else):

DiskFileUpload upload = new DiskFileUpload();
upload.setSizeMax(2000000); //max. file size 2M
List items = upload.parseRequest(portletRequest);
Iterator iter = items.iterator();
while (iter.hasNext()) {
// although it is named a FileItem it is actually a form input
FileItem item = (FileItem)iter.next();
// check whether it is the file being uploaded or a mere form input field
if (!item.isFormField()) {
// this is a file
String fileName = item.getName();
File location = new File(destinationDirectory + "/" + fileName);
item.write(location);
}
else
{
// this is a plain form field
String formFieldName = item.getFieldName();
String formFieldValue = item.getString();

}
}

Awkward.

Share
Categories
Java SQL Server

SQL Server 2000 with Tomcat

My page on creating a DataSource in Tomcat with SQL Server 2000

Share
Categories
Java

Converting an ArrayList to a single-typed Array

Supposedly you want to create an object that dynamically takes object parameters and stores them in an ArrayList. All of the objects are of the same type and instead of creating a new array every time you use an ArrayList because you can keep on adding objects to it and it will still retain the order.
Now, suppose want to get an new array of the type of objects that you put in the ArrayList back. You can use ArrayList‘s toArray() method, and get an array of Object objects. Or you can use the following call:

MyObject [] objectArray = (MyObject[])theArrayList.toArray(new MyObject[0]);

Grizzly but true.

Share
Share