How do I upload a file to a servlet?
Author: Deron Eriksson
Description: This tutorial describes how to upload a file to a servlet.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0) || Tomcat 5.5.20
(Continued from page 1) If we just try hitting the TestServlet, we can see that it tells us that it didn't receive the multipart form data. ![]() Now, let's upload some files via our upload.jsp. I clicked the first Browse button and browsed to a 'test.txt' file. I clicked the second Browse button and browsed to a 'test.html' file. I intentionally left the third file field blank. ![]() The test.txt file is shown below. test.txtthis is some text in test.txt The test.html file is shown below. test.htmlhere is some text in test.html After selecting 'test.txt' and 'test.html' on my upload.jsp, I clicked the Upload button. This submitted the form data to the TestServlet. As you can see, all four fields of the form were read by the servletW. The servlet is able to differentiate a regular field from a form field via the FileItem's isFormField() method, which returns true if the field is a regular field. For file fields, we can see that a good deal of information is being displayed, including the field name, the String content of the file, the name of the file, the content type, the file size in bytes, and the result of calling toString() on the FileItem. In addition, you can call get() on the FileItem object to get the content of the file as a byte array. You can also get an InputStream and an OutputStream from FileItem. ![]() The ApacheSW Commons FileUploadS library makes it remarkably easy to upload files to a servlet. |