Open In App

How to Upload Multiple Files using Java Servlet?

Last Updated : 15 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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"?>
         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:

index.jsp Output

 

Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads