Servlet - Uploading File

Last Updated : 16 May, 2026

Servlets are server-side Java programs used to process client requests and generate dynamic web responses. Using Servlets, files can be uploaded from a client system to the server through an HTML form. For file uploading, the request data is handled as multipart form data.

  • Used to upload files such as images, documents, and PDFs to the server.
  • Requires the form method to be set to POST.
  • Uses multipart/form-data encoding to transfer file data.

Working Flow of File Upload

The diagram below illustrates the complete workflow of file uploading in a Servlet-based web application, showing how the multipart request is processed by the servlet container, controller, and service layer before storing the uploaded file on the server or database.

Servlet - Creating a File Upload Form
  • User selects a file and submits the upload form.
  • The request is sent to the Servlet Container through web.xml configuration.
  • MultipartFilter intercepts and processes the multipart request.
  • The request is forwarded to the DispatcherServlet.
  • DispatcherServlet sends the request to the Controller.
  • Controller accesses the uploaded file using MultipartFile.
  • MultipartFile interacts with the Servlet Part object for file handling.
  • Controller forwards file data to the Service layer.
  • Service layer stores the file in the upload directory or database.
  • StandardServletMultipartResolver resolves multipart content.
  • The uploaded file is temporarily stored by the Servlet Container before final storage.

Important Methods Used

Method

Description

request.getPart()

Retrieves uploaded file part

getSubmittedFileName()

Returns uploaded file name

write()

Saves file to server

mkdir()

Creates upload directory

Step-by-step implementation to upload a File

Follow these steps to upload a files using sevlet in a Application.

Step 1: Create Dynamic Web Project

We will create a dynamic web project in Eclipse and the project structure will look like the below image.

Step 2: Add Required JAR File

There are several options for uploading a file to the server. However, we are going to utilize O'Reilly's MultipartRequest class. We will need the cos.jar file to use this class.

Step 3: Create Upload Form (index.html)

Create an HTML form to select and upload the file.

HTML
<html>  
<body>  
<form action="GoGfg" method="post" enctype="multipart/form-data">  
Select File:<input type="file" name="fname"/><br/>  
<input type="submit" value="upload"/>  
</form>  
</body>  
</html>  

Step 4: Create Servlet for File Upload

File uploadDir = new File(path) creates a File object for the upload directory, while uploadDir.exists() checks whether the folder is already present. If the directory does not exist, mkdir() automatically creates it, avoiding manual folder creation.

Example:

Java
import com.oreilly.servlet.MultipartRequest;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Servlet class
public class GfgFileUpload extends HttpServlet {

    // Handle POST request
    @Override
    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, IOException
    {

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        // Upload directory path
        String path = "C:\\\\temp";

        // Create File object
        File uploadDir = new File(path);

        // Create directory if it does not exist
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        // Upload file
        MultipartRequest m
            = new MultipartRequest(request, path);

        out.print("File uploaded successfully");
    }
}

Step 5: Configure web.xml

Maps URL /GoGfg to GfgFileUpload servlet When form submits, request goes to servlet

XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
   <servlet-name>GfgFileUpload</servlet-name>
   <servlet-class>GfgFileUpload</servlet-class>
</servlet>

<servlet-mapping>
   <servlet-name>GfgFileUpload</servlet-name>
   <url-pattern>/GoGfg</url-pattern>
</servlet-mapping>
</web-app>

  Step 6: Run the Application

  • Start Apache Tomcat Server
  • Deploy the project
  • Open browser:

http://localhost:8080/GfgUpload/index.html

Output:

  • Browser loads upload form
  • User selects file and clicks upload


 

Step 2: After Clicking on the upload button file will be uploaded to the C:\\temp location

Explanation: The servlet receives the uploaded file from the HTML form as a multipart request and processes it using the MultipartRequest class. It checks and creates the upload directory if it does not exist, then stores the file in the specified server path. Finally, it sends a success response back to the client after completing the upload operation.

Comment