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.1. Preparing the HTML Page for File Uploads

Problem

You want to set up an HTML page to allow the user to specify a file from his filesystem to upload to the server.

Solution

Use the HTML form tag with its enctype attribute set to "multipart/form-data". Use an input tag nested in the form tag with a type attribute of "file".

Discussion

The HTML for file uploading involves a few "must haves." The form tag specifies the servlet (or other server-side component) that is handling the file upload in its action attribute. The method attribute must be POST (not GET) for the file upload action to work. The form tag's enctype attribute must be "multipart/form-data".

The widget with which the user enters the file to upload is an input tag with a type of "file", and looks like a text field. The name attribute uniquely names the particular input tag, which becomes important when the HTML specifies the uploading of more than one file (see the note at the end of this recipe). Without any additional intervention, the server saves the uploaded file with its original filename. The accept attribute is designed to limit the file types that the user can choose for uploading, such as to the "application/pdf" MIME type, but this attribute has poor support among browsers.

When displaying the HTML in Example 8-2, browsers automatically show a Browse button. When the form client selects the button, the browser displays a typical filesystem navigation window with which the user can select the file.

Example 8-2. Simple ...

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