Upload File to Server Using Servlet Example

Here you will get example to upload file to server using servlet.

File uploading is a very common and important feature of any website. In servlet it can be done in many ways. But in this tutorial I am sharing the two most commonly used methods.

Also Read: Download File From Server Using Servlet Example

How to Upload File to Server Using Servlet?

Method 1: Servlet 3.0

If you are using Servlet 3.0 version then it provides option for uploading files without using any third party library.

Below example shows how to do this.

Create a dynamic web project and add following source code in respective files.

WebContent/index.html

This page gives an option for choosing a file for uploading.

WebContent/success.html

This page is opened if uploading is successful.

src/com/Upload.java

This servlet is responsible for uploading the file to server.

Method 2: Apache Commons Library

Apache commons provides some utility classes for uploading file. Download following two jars and import them in your project.

  1. Download Apache Commons FileUpload
  2. Download Apache Commons IO

Also Read: How to Add or Import Jar in Eclipse Project

Now Create a dynamic web project and add following source code in respective files.

WebContent/index.html

WebContent/success.html

src/com/Upload.java

How to upload multiple files?

In above example I have uploaded only one file. The example will work for uploading multiple files also. You have to just add multiple attribute in file input tag on index.html.

Comment below if you have any queries or know any other method for uploading files to server using servlet.

Leave a Reply

Your email address will not be published. Required fields are marked *