Tutorials Logic, IN info@tutorialslogic.com

Servlet File Upload MultipartRequest, Apache Commons: Tutorial, Examples, FAQs & Interview Tips

Servlet File Upload MultipartRequest, Apache Commons

Servlet File Upload MultipartRequest, Apache Commons is an important Servlet topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.

For this page, focus on what problem Servlet File Upload MultipartRequest, Apache Commons solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .

A strong understanding of Servlet File Upload MultipartRequest, Apache Commons should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.

Servlet File Upload MultipartRequest Apache Commons should be studied as a practical Servlet lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the servlet > file-upload page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

@MultipartConfig and Part Interface

Servlet 3.0 introduced built-in multipart/form-data support via the @MultipartConfig annotation and the Part interface. No third-party library is needed.

  • @MultipartConfig - Annotates the servlet to handle multipart requests. Configures file size limits and temp storage.
  • request.getPart(name) - Returns a single Part for the given field name.
  • request.getParts() - Returns all parts (for multiple file uploads).
  • Part.write(path) - Saves the uploaded file to disk.

Single File Upload Servlet

Single File Upload Servlet
package com.example;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;
import java.nio.file.*;

@WebServlet("/upload")
@MultipartConfig(
    fileSizeThreshold = 1024 * 1024,      // 1 MB - write to disk if larger
    maxFileSize       = 1024 * 1024 * 10, // 10 MB max per file
    maxRequestSize    = 1024 * 1024 * 50  // 50 MB max total request
)
public class FileUploadServlet extends HttpServlet {

    // Directory to save uploaded files (outside webroot for security)
    private static final String UPLOAD_DIR = "/var/uploads/";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/views/upload.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Get the uploaded file part
        Part filePart = request.getPart("file");

        // Get the original filename submitted by the browser
        String fileName = getFileName(filePart);

        if (fileName == null || fileName.isEmpty()) {
            request.setAttribute("error", "No file selected.");
            request.getRequestDispatcher("/WEB-INF/views/upload.jsp").forward(request, response);
            return;
        }

        // Validate file type (only images allowed)
        String contentType = filePart.getContentType();
        if (!contentType.startsWith("image/")) {
            request.setAttribute("error", "Only image files are allowed.");
            request.getRequestDispatcher("/WEB-INF/views/upload.jsp").forward(request, response);
            return;
        }

        // Save the file to the upload directory
        Path uploadPath = Paths.get(UPLOAD_DIR);
        if (!Files.exists(uploadPath)) Files.createDirectories(uploadPath);

        filePart.write(UPLOAD_DIR + fileName);

        request.setAttribute("message", "File '" + fileName + "' uploaded successfully.");
        request.getRequestDispatcher("/WEB-INF/views/upload.jsp").forward(request, response);
    }

    // Extract filename from Content-Disposition header
    private String getFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        for (String token : contentDisposition.split(";")) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf('=') + 1).trim()
                            .replace("\"", "");
            }
        }
        return null;
    }
}

@MultipartConfig and Part Interface

@MultipartConfig and Part Interface
<%-- WEB-INF/views/upload.jsp --%>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head><title>File Upload</title></head>
<body>
    <h2>Upload File</h2>
    <c:if test="${not empty message}">
        <p style="color:green;">${message}</p>
    </c:if>
    <c:if test="${not empty error}">
        <p style="color:red;">${error}</p>
    </c:if>
    <!-- enctype="multipart/form-data" is REQUIRED for file uploads -->
    <form action="${pageContext.request.contextPath}/upload"
          method="post" enctype="multipart/form-data">
        <label>Select file: <input type="file" name="file" accept="image/*" /></label>
        <br/><br/>
        <button type="submit">Upload</button>
    </form>
</body>
</html>

Multiple File Upload

Multiple File Upload with Validation

Multiple File Upload with Validation
@WebServlet("/multi-upload")
@MultipartConfig(maxFileSize = 1024 * 1024 * 5) // 5 MB per file
public class MultiUploadServlet extends HttpServlet {

    private static final String UPLOAD_DIR = "/var/uploads/";
    private static final Set<String> ALLOWED_TYPES = Set.of(
            "image/jpeg", "image/png", "image/gif", "application/pdf");

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        List<String> uploaded = new ArrayList<>();
        List<String> errors   = new ArrayList<>();

        // Iterate over all parts in the multipart request
        for (Part part : request.getParts()) {
            // Skip non-file fields (text inputs, etc.)
            if (part.getContentType() == null) continue;

            String fileName = getFileName(part);
            if (fileName == null || fileName.isEmpty()) continue;

            // Validate MIME type
            if (!ALLOWED_TYPES.contains(part.getContentType())) {
                errors.add(fileName + ": unsupported file type.");
                continue;
            }

            // Validate file size (redundant with @MultipartConfig but explicit)
            if (part.getSize() > 5 * 1024 * 1024) {
                errors.add(fileName + ": exceeds 5 MB limit.");
                continue;
            }

            // Save file
            part.write(UPLOAD_DIR + fileName);
            uploaded.add(fileName);
        }

        request.setAttribute("uploaded", uploaded);
        request.setAttribute("errors",   errors);
        request.getRequestDispatcher("/WEB-INF/views/upload-result.jsp")
               .forward(request, response);
    }

    private String getFileName(Part part) {
        String cd = part.getHeader("content-disposition");
        if (cd == null) return null;
        for (String token : cd.split(";")) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
}

@MultipartConfig Attributes

Attribute Default Description
location "" Temp directory for parts during processing
maxFileSize -1 (unlimited) Max size in bytes for a single uploaded file
maxRequestSize -1 (unlimited) Max size in bytes for the entire multipart request
fileSizeThreshold 0 File size above which the part is written to disk (vs memory)

HTML Form for Multiple File Upload

HTML Form for Multiple File Upload
<%-- multi-upload.jsp --%>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head><title>Multiple File Upload</title></head>
<body>
    <h2>Upload Multiple Files</h2>
    <form action="${pageContext.request.contextPath}/multi-upload"
          method="post" enctype="multipart/form-data">

        <!-- multiple attribute allows selecting multiple files -->
        <label>Select files:
            <input type="file" name="files" multiple
                   accept=".jpg,.jpeg,.png,.gif,.pdf" />
        </label>
        <br/><br/>
        <button type="submit">Upload All</button>
    </form>
</body>
</html>

Detailed Learning Notes for Servlet File Upload MultipartRequest, Apache Commons

When studying Servlet File Upload MultipartRequest, Apache Commons, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.

In Servlet, Servlet File Upload MultipartRequest, Apache Commons becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.

  • Identify the main problem this topic solves.
  • Write the smallest possible working example.
  • Change one input or option and observe the result.
  • Note the mistake that would break the example.

Servlet File Upload MultipartRequest Apache Commons Java review example

Servlet File Upload MultipartRequest Apache Commons Java review example
class ServletFileUploadMultipartRequestApacheCommonsReview {
    public static void main(String[] args) {
        String state = "ready";
        System.out.println("Servlet File Upload MultipartRequest Apache Commons: " + state);
    }
}

Servlet File Upload MultipartRequest Apache Commons guard example

Servlet File Upload MultipartRequest Apache Commons guard example
String value = null;
if (value == null) {
    System.out.println("Servlet File Upload MultipartRequest Apache Commons: handle the missing value before continuing");
}
Key Takeaways
  • Explain the purpose of Servlet File Upload MultipartRequest, Apache Commons before memorizing syntax.
  • Run or trace one small Servlet example and confirm the output.
  • Test one normal case, one edge case, and one mistake case for Servlet File Upload MultipartRequest, Apache Commons.
  • Write the rule in your own words after checking the example.
  • Connect Servlet File Upload MultipartRequest, Apache Commons to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Memorizing Servlet File Upload MultipartRequest Apache Commons without the situation where it is useful.
RIGHT Connect Servlet File Upload MultipartRequest Apache Commons to a concrete Servlet task.
Purpose makes syntax easier to recall.
WRONG Testing Servlet File Upload MultipartRequest Apache Commons only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to Servlet File Upload MultipartRequest Apache Commons.
Evidence keeps debugging focused.
WRONG Memorizing Servlet File Upload MultipartRequest Apache Commons without the situation where it is useful.
RIGHT Connect Servlet File Upload MultipartRequest Apache Commons to a concrete Servlet task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to Servlet File Upload MultipartRequest, Apache Commons, then fix it and explain the fix.
  • Summarize when to use Servlet File Upload MultipartRequest, Apache Commons and when another approach is better.
  • Write a small example that uses Servlet File Upload MultipartRequest Apache Commons in a realistic Servlet scenario.
  • Change one important value in the Servlet File Upload MultipartRequest Apache Commons example and predict the result first.

Frequently Asked Questions

The common mistake is memorizing syntax without understanding when the behavior changes or fails.

Remember the problem it solves in Servlet, then attach the syntax or steps to that problem.

You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.

They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.