JSP and Beyond

a pragmatic primer on building web-based solutions with Java technologies

File Uploads

Similar to the email functionality covered in the previous section, you will need to go some extra distance to enable file uploads from within your JSP-based application. This is important because most web-based applications will need to accept files at some point, whether a document or image. When a web page is submitted that contains a file to be uploaded, the data is sent as a HTTP POST encoded using the MIME-type multipart/form-data. You will have to manually handle the stream to combine it back into the original file within your code where it can then be saved on your server.

Thankfully, people have realized this and created pre-packaged beans and classes to handle file uploads. Some are commercial, but fortunately the Apache Foundation has developed a library to help manage uploads that is freely available at:


The code sample below highlights the code from Apache foundation.

public void doPost(HttpServletRequest req, HttpServletResponse res)
DiskFileUpload fu = new DiskFileUpload();
// maximum size before a FileUploadException will be thrown
// maximum size that will be stored in memory
// the location for saving data that is larger than getSizeThreshold()

List fileItems = fu.parseRequest(req);
// assume we know there are two files. The first file is a small
// text file, the second is unknown and is written to a file on
// the server
Iterator i = fileItems.iterator();
String comment = ((FileItem)i.next()).getString();
FileItem fi = (FileItem)i.next();
// filename on the client
String fileName = fi.getName();
// save comment and filename to database

// write the file
fi.write(”/www/uploads/” + fileName);