How do I upload a file to my servlet or JSP?
On the client side, the client's browser must support form-based upload. Most modern browsers do, but there's no guarantee. For example,
<FORM ENCTYPE='multipart/form-data' method='POST' action='/myservlet'>
<INPUT TYPE='file' NAME='mptest'>
<INPUT TYPE='submit' VALUE='upload'>
</FORM>
The input type "file" brings up a button for a file select box on the browser together with a text field that takes the file name once selected. The servlet can use the GET method parameters to decide what to do with the upload while the POST body of the request contains the file data to parse.When the user clicks the "Upload" button, the client browser locates the local file and sends it using HTTP POST, encoded using the MIME-type multipart/form-data. When it reaches your servlet, your servlet must process the POST data in order to extract the encoded file. You can learn all about this format in RFC 1867.
Unfortunately, there is no method in the Servlet API to do this. Fortunately, there are a number of libraries available that do. Some of these assume that you will be writing the file to disk; others return the data as an InputStream.
- Jason Hunter's MultipartRequest (available from http://www.servlets.com/)
- Apache Jakarta Commons Upload (package org.apache.commons.upload) "makes it easy to add robust, high-performance, file upload capability to your servlets and web applications"
- CParseRFC1867 (available from http://www.servletcentral.com/).
- HttpMultiPartParser by Anil Hemrajani, at the isavvix Code Exchange
- There is a multipart/form parser availailable from Anders Kristensen (http://www-uk.hpl.hp.com/people/ak/java/, ak@hplb.hpl.hp.com) at http://www-uk.hpl.hp.com/people/ak/java/#utils.
- JavaMail also has MIME-parsing routines (see the Purple Servlet References).
- Jun Inamori has written a class called org.apache.tomcat.request.ParseMime which is available in the Tomcat CVS tree.
- JSPSmart has a free set of JSP for doing file upload and download.
- UploadBean by JavaZoom claims to handle most of the hassle of uploading for you, including writing to disk or memory.
- There's an Upload Tag in dotJ
Please note that you can't access a file on the client system directly from a servlet; that would be a huge security hole. You have to ask the user for permission, and currently form-based upload is the only way to do that.
No comments:
Post a Comment