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

Page: < 1 2

(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.

Hitting test servlet without uploading

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.

Setting files to upload via upload.jsp

The test.txt file is shown below.


this is some text in test.txt

The test.html file is shown below.


here 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.

Uploaded files to test servlet

The ApacheSW Commons FileUploadS library makes it remarkably easy to upload files to a servlet.

Page: < 1 2