How to upload files to a servlet

In this tutorial, we discuss how to upload files to a servlet.

Parsing the uploaded file in the servlet depends strictly on the used version of the servlet API, here below we explain how to do this in versions 3.1, 3.0 and 2.5 respectively.

1- Upload.html

Before digging into the servlet, let’s see how would the HTML form looks like:

The above is a very simple HTML form which only holds an input file along with a submit button.

As noticed, we set the encoding type to “multipart/form-data” and define “FileUpload” servlet to handle the request.

2- Servlet 3.1 (Tomcat 8)

In order to parse the uploaded file in Servlet 3.1, first of all, you have to annotate your servlet with @MultipartConfig as the following:

Inside your doPost(), you can parse the uploaded file using request.getPart() method and read the uploaded file name using getSubmittedFileName().

In the following example, we read the uploaded file and write it in the file system:

3- Servlet 3.0 (Tomcat 7)

With Servlet 3.0, we can read the uploaded file just as we did with Servlet 3.1.

The only difference between the 2 versions is how to read the uploaded file name, the getSubmittedFileName() method is not supported in Servlet 3.0.

So, in order to read the uploaded file name, we create a custom utility method which parses the request header and read the file name from within it:

4- Servlet 2.5 (Tomcat 6)

Well, with Servlet 2.5, things are a bit different, there is no predefined API to read the uploaded files in this version.

So if you’re still using this version and want to read the uploaded files, we recommend the Apache Commons library.

In order to use Apache Commons, you have to add commons-fileupload-1.4.jar and commons-io-2.6.jar to your classpath.

After that, you can parse the uploaded file as below:

Hussein Terek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

avatar