VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-upload-multiple-files-using-java-servlet/

⇱ How to Upload Multiple Files using Java Servlet? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Upload Multiple Files using Java Servlet?

Last Updated : 23 Jul, 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.

web.xml

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)

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

index.jsp:

👁 index.jsp Output
 

Output:

👁 Image
 
Comment
Article Tags:
Article Tags: