CLOSE ✕
Get in Touch
Thank you for your interest! Please fill out the form below if you would like to work together.

Thank you! Your submission has been received!

Oops! Something went wrong while submitting the form

Upload File Using JSP

Neelanshi Sharma
|
JSP
|
Jan 25, 2021

A JSP can be used with an HTML form tag to allow users to upload files to the server. An uploaded file can be a text file or a binary or an image file or just any document. There are many ways to upload the file to the server. One of the way is by the MultipartRequest class. For using this class you need to have the cos.jar file.

MultipartRequest class

It is a utility class to handle the multipart/form-data request. There are many constructors defined in the MultipartRequest class.

1. MultipartRequest(HttpServletRequest request, String saveDirectory) uploads the file upto 1MB.

2. MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize) uploads the file upto specified post size.

3. MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize, String encoding) uploads the file upto specified post size with given encoding.

Creating a File Upload Form

To upload a file on server we can make use of <form> tag. It can be written as follows:

Following are the important points to be noted down −

1. The form method attribute should be set to POST method and GET method can not be used.

2. The form enctype attribute should be set to multipart/form-data.

3. The form action attribute should be set to a JSP file which would handle file uploading at backend server. Following example is using uploadFile.jsp program file to upload file.

4. To upload a single file you should use a single <input .../> tag with attribute type = "file". To allow multiple files uploading, include more than one input tag with different values for the name attribute. The browser associates a Browse button with each of them.

Functionality of Post Method

Here we have doPost() method in IconUpload.java, which will be called as we are passing POST method in JSP and it will have request and response objects as its parameters.

1. First set the type of response we will get after processing this request using response.setContentType().

2. Extract file name and define paths to save the file to be uploaded. This is done in extractFileName() below.

3. Within the try and catch block very simple work is done. Basically, an instance of PrintWriter writes the file content byte by byte and saves it to the specified location at server.

4. Redirect it to next page using response.sendRedirect().

And there you go!!

Neelanshi Sharma
Neelanshi is a mobile and web developer. She is a computer science major from Banasthali Vidyapith, India.

Recent Blog Posts

Lets Work Together
Contact Me