Categories
Java

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

Tackling file uploads from froms encoded as multipart/form-data using the Apache Jakarta Commons FileUpload package

Share

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

Leave a Reply

Your email address will not be published. Required fields are marked *

 

Share