Servlets File Uploading - Java Servlets

What is Servlets File Uploading?

A Servlet can be used with an HTML form tag to let users to upload files to the server. An uploaded file might be a text file or image file or any document.

Creating a File Upload Form

The resulting HTM code below creates an uploader form. Resulting are the important points to be noted down −

  • The form method attribute should be set to POST method and GET method can not be used
  • The form enctype attribute should be set to multipart/form-data.
  • The form action attribute must be set to a servlet file which would handle file uploading at backend server. Resulting instance is using UploadServlet servlet to upload file.
  • To upload a single file you must use a single <input .../> tag with attribute type="file". To let multiple files uploading, include more than one input tags with different values for the name attribute. The browser associates a Browse button with each of them.

This will show resulting result which would permit to select a file from local PC and when user would click at "Upload File", form would be submitted along with the selected fil –
File Upload:

Writing Backend Servlet

Resulting is the servlet UploadServlet which would take care of accepting uploaded file and to store it in directory <Tomcat-installation-directory>/webapps/data. This directory name could also be added using an external configuration such as a context-param element in web.xml as follows –

Resulting is the source code for UploadServlet which can handle multiple file uploading at a time. Earlier taking place you have make sure the followings −

  • Resulting instance depends on FileUpload, so make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from
  • FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from
  • While testing resulting instance, you should upload a file which has less size than maxFileSize otherwise file would not be uploaded.
  • Make sure you have created directories c:\temp and c:\apache-tomcat8.0.28\webapps\data well in advance.

Compile and Running Servlet

Compile above servlet UploadServlet and create required entry in web.xml file as follows.

Currently try to upload files using the HTML form which you produced above. When you would try http://localhost:8080/UploadFile.htm, it would show subsequent result which would help you uploading any file from your local machine.

File Upload:

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Java Servlets Topics