O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.3. Uploading One File at a Time

Problem

You want to create a component that can receive a client file upload and store the file in a local directory.

Solution

Create a servlet that uses the com.oreilly.servlet.MultipartRequest class from Jason Hunter's cos.jar archive.

Discussion

The MultipartRequest class includes several overloaded constructors. The one used in Example 8-3 takes the javax.servlet.http.HttpServletRequest object, the path to the directory where you want to save uploaded files, and the size limit for the file as parameters. In Example 8-3, if the client uploads a file that exceeds 5 MB, then the UploadServlet throws a java.io.IOException. You can allow this exception to be managed by an error-page element in web.xml for IOExceptions, as Example 8-3 does, or use a try/catch block in the upload servlet to deal with errors.

Tip

See Chapter 9 for how to declare error pages for the web application.

With MultipartRequest, as soon as the code instantiates the object, the object is handling the file upload; in other words, you do not have to call a method to commence managing the upload.

The servlet in Example 8-3 initiates the file upload and then displays the name of the uploaded file(s).

Example 8-3. A servlet that uses the MultipartRequest class

package com.jspservletcookbook;           

import javax.servlet.*;
import javax.servlet.http.*;import com.oreilly.servlet.MultipartRequest;
import java.util.Enumeration;

public class UploadServlet extends HttpServlet {
   
    private String webTempPath; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required