This is a bit late, but allow me to suggest Jakarta Commons' FileUpload package.
Your code using it will look a little bit like this: (this sample uses a HashTable as a return because I wanted to be able to store all the request's elements using key/value pairs regardless of their object type -- there is probably a better way of doing this, but it's entirely functional.)
This process() method is meant to be part of a helper object to which you feed your request and the root directory. Your controller servlet can get the root path in HttpServlet.init(ServletConfig cfg) by calling cfg.getServletContext().getRealPath("/") -- you have to do it this way, because calling request.getContextPath(), for instance from a JSP, just gives you the URL root, not the filesystem root. If you don't know enough about servlet programming for this to make sense, you need to learn more than I can teach you in one or two posts; all I could do is recommend a few books.
Refer to the FileUpload JavaDocs for function reference, of course.
code:
public static HashTable process(HttpServletRequest request, String rootDir)
throws FileUploadException, IOException
{
HttpSession session = request.getSession();
boolean isMultipart = FileUpload.isMultipartContent(request);
if (!isMultipart) // text only, just get request elements
{
Enumeration paramKeys = request.getParameterNames();
Hashtable result = new Hashtable();
while (paramKeys.hasMoreElements())
{
String keyName = (String)paramKeys.nextElement();
result.put(keyName, request.getParameter(keyName));
}
return result;
}
// get uploaded file items from request
DiskFileUpload upload = new DiskFileUpload();
upload.setSizeThreshold(4096);
upload.setSizeMax(1000000); // max 1 MB
List uploadedItems = upload.parseRequest(request);
Iterator itemIter = uploadedItems.iterator();
Hashtable result = new Hashtable(
Math.round(uploadedItems.size() / 0.75f));
// save images to disk
while (itemIter.hasNext())
{
FileItem item = (FileItem)itemIter.next();
if (item.isFormField())
{
// place string value in result
result.put(item.getFieldName(), item.getString());
}
else // item is a file; process upload and place filepath in result
{
// name uploaded file using your own criteria
String destFilename = rootDir + "i_generated_this_filename.yay";
// write image to file
File uploadedFile = new File(destFilename);
item.write(uploadedFile);
// save file upload location to result
result.put(item.getFieldName(), uploadedFile.getPath());
}
}
return result;
}
Cell 1250 :: alanmacdougall.com :: Illustrator tips