|[ Team LiB ]|
Recipe 8.1 Preparing the HTML Page for File Uploads
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".
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.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Please Choose The File</title> </head> <body bgcolor="#ffffff"> <table border="0"><tr> <form action="/home/servlet/com.jspservletcookbook.UploadServlet" method="post" enctype="multipart/form-data"> <td valign="top"><strong>Please choose your document:</strong><br></td> <td> <input type="file" name="file1"> <br><br> </td></tr> <tr><td><input type="submit" value="Upload File"></td></tr> </form> </table> </body> </html>
After selection, the text field displays the full path to the selected file. Figure 8-1 shows this HTML page in a web browser.
Figure 8-1 shows the input field after the user has already chosen the file. The browser then automatically fills in the text field with the complete file path.
Recipe 8.4 on using the com.oreilly.servlet library for file uploading; Recipe 8.5 on handling a single file upload; Recipe 8.6 on handling multiple file uploads; Recipe 8.5 on controlling file naming; Recipe 8.6 on using a JSP to handle file uploads; the homepage for com.oreilly.servlet: http://www.servlets.com/cos/index.html; the RFC 1867 document on form-based file uploads: http://www.ietf.org/rfc/rfc1867.txt.
|[ Team LiB ]|