Thursday, July 3, 2008

Uploading Files with JSP

By Nisansa Perera

I was fed up with some of the resources available on the net to do this.

This is how I got this done.

1. Enable your html to upload files



Please specify a file, or a set of files:








2. Use commons file upload

Then follow Apache commons file upload article to handle the file within your jsp. This is the code snippet to do that, extracted from commons file upload user guide.


// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();

// Set factory constraints
factory.setSizeThreshold(yourMaxMemorySize);
factory.setRepository(yourTempDirectory);

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// Set overall request size constraint
upload.setSizeMax(yourMaxRequestSize);

// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();

if (!item.isFormField()) {

// Process a file upload
if (writeToFile) {
File uploadedFile = new File(...);
item.write(uploadedFile);
} else {
InputStream uploadedStream = item.getInputStream();
...
uploadedStream.close();
}
}
}

For more information on commons file upload, use the their user guide.
References
  • http://www.cs.tut.fi/~jkorpela/forms/file.html
  • http://commons.apache.org/fileupload/using.html