How to Upload Multiple Files using Java Servlet?
Last Updated :
26 Apr, 2025
Servlets are the server-side programs used to create dynamic web pages. They can be used to upload files on the server. This article shows two approaches for uploading multiple files on the server.
index.jsp
- Set method: This is an attribute of <form> tag which is used to specify the http method used to send the data. HTTP provides GET and POST methods to transfer data over the network. To send files to the server, HTTP POST method is used.
- Set enctype: This is an attribute of <form> tag which specifies the type of encryption used to encrypt the data sent through the POST method. HTML forms provide three types of encryption:
1. application/x-www-form-urlencoded (the default)
2. multipart/form-data
3. text/plain
In order to send files through HTML form, 'multipart/form-data' is used.
HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Upload Multiple Files</title>
</head>
<body>
<form method="post" action="FileUploadServlet" enctype="multipart/form-data">
<h3>Choose files to upload...</h3>
<input type="file" name="file1"/><br><br>
<input type="file" name="file2"/><br><br>
<input type="file" name="file3"/><br><br>
<input type="submit"/>
</form>
</body>
</html>
web.xml
XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>FileUploadUsingCos</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>FileUploadServlet</display-name>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>servlets.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/FileUploadServlet</url-pattern>
</servlet-mapping>
</web-app>
File upload using cos.jar
Before Java EE 6, separate jar files like Apache's commons-fileupload were required to enable file upload functionalities in the application. Given below is an example to demonstrate the same.
Download cos.jar from the below link: https://jar-download.com/maven-repository-class-search.php?search_box=com.oreilly.servlet.MultipartRequest
FileUploadServlet.java
MultipartRequest is a utility class present in cos.jar which is used to handle the multipart data received from HTML form. It reads the files and saves them directly to the disk in the constructor itself.
It provides several constructors to specify the upload path, file size, etc.Â
- MultipartRequest(javax.servlet.http.HttpServletRequest request, java.lang.String saveDirectory)
- MultipartRequest(javax.servlet.http.HttpServletRequest request, java.lang.String saveDirectory, int maxPostSize)
It can also be used to get parameters using the following method :Â
java.lang.String getParameter(java.lang.String name)
Java
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oreilly.servlet.MultipartRequest;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer=response.getWriter();
response.setContentType("text/html");
String path=getServletContext().getRealPath("");
MultipartRequest mpr=new MultipartRequest(request,path,20*1024*1024);
writer.println("Your files are uploaded!");
}
}
File upload using Servlet 3.x API
@MultipartConfig annotation is provided to handle multipart data. It consists of the following parameters:
- maxFileSize
- location
- fileSizeThreshold
Part is an interface that represents a part or form item that was received within a multipart/form-data POST request. Useful methods of a Part interface are :
- void delete()
- InputStream getInputStream()
- void write(String fileName)
The following methods of HttpServletRequest are used to obtain Part objects:
- Part getPart(java.lang.String name)
- java.util.Collection<Part> getParts()
FileUploadServlet.java
Java
package servlets;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet("/FileUploadServlet")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path=getServletContext().getRealPath("");
for(Part p : request.getParts())
{
p.write(path+File.separator+extractFileName(p));
}
response.getWriter().println("Your files are uploaded!");
}
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
}
index.jsp:
Â
Output:
Â
Similar Reads
Upload Multiple Files in Spring Boot using JPA, Thymeleaf, Multipart
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
8 min read
URL Rewriting using Java Servlet
Url rewriting is a process of appending or modifying any url structure while loading a page. The request made by client is always a new request and the server can not identify whether the current request is send by a new client or the previous same client. Due to This property of HTTP protocol and W
5 min read
How to Get a List of Files From the SFTP Server in Java?
In this tutorial, we'll talk about how to use Java to retrieve a list of files from an SFTP server. We will use SSHClient for creating an SFTP client. First, add a maven dependency to your project. Java <dependency> <groupId>com.hierynomus</groupId> <artifactId>sshj</artif
2 min read
How to Create Servlet in MyEclipse IDE?
Servlets are Java programs that extend the capabilities of a Web Server. It runs on a Java-enabled web server like Apache Tomcat server, to receive and respond to the client's requests. With Servlets, we can create Enterprise-grade applications with database access, session management, and content g
8 min read
How to Run Servlet in Tomcat?
In this example, we will create a basic servlet that displays a Hello World message from a Java program to the user in the browser without using any Java IDE like Eclipse. Note: Running a server like Tomcat to run our servlet. if it is not already installed, you can install it using this article: Ho
3 min read
Connecting to an SFTP Server using Java JSch Library
SFTP (Secure File Transfer Protocol) is a secure way to transfer files between a client and a server. It is similar to FTP (File Transfer Protocol) but is more secure as it uses SSH (Secure Shell) to encrypt the data being transferred. In this article, we will learn how to connect to an SFTP server
3 min read
JSP - File Uploading
In this article, we will learn about how to upload a file to a server using JSP. JSP stands for Java Server Pages. JSP is a server-side web technology, traditionally used to create dynamic web pages. Before that, servlets were highly used to create dynamic web pages, in that HTML tags are inserted i
6 min read
How to Download Files From SFTP Server in Java?
A network protocol called SSH, commonly referred to as Secure Shell or Secure Socket Shell, enables a secure connection between two computers across an insecure network. This tutorial will show you how to connect to a remote SFTP server using Java and the SSH client. Host key verification must be t
3 min read
How to Make get() Method Request in Java Spring?
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
3 min read
Hidden Form Field using Annotation | Java Servlet
Hidden form field is used to store session information of a client. In this method, we create a hidden form which passes the control to the servlet whose path is given in the form action area. Using this, the information of the user is stored and passed to the location where we want to send data. Th
4 min read