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,
The input type &quot;file&quot; 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.<FORM ENCTYPE='multipart/form-data' method='POST' action='/myservlet'> <INPUT TYPE='file' NAME='mptest'> <INPUT TYPE='submit' VALUE='upload'> </FORM>
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.
Jason Hunter's MultipartRequest (available from http://www.servlets.com)
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/, email@example.com)
- 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
Once you process the form-data stream into the uploaded file, you can then either write it to disk, write it to a database, or process it as an InputStream, depending on your needs. See How can I access or create a file or folder in the current directory from inside a servlet? and other questions in the Servlets:Files Topic for information on writing files from a Servlet.
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.
[This FAQ based on earlier posts by Thomas Moore, Detlef Pleiss (firstname.lastname@example.org), and others.]