Java Servlet upload file
last modified November 30, 2026
Java Servlet upload file shows how to upload a single file in a Java web application using servlet technology.
Java Servlet
Servlet is a Java class which responds to a particular type of network request - most commonly an HTTP request. Java servlets are used to create web applications. They run in servlet containers such as Tomcat or Jetty. Modern-day Java web development uses frameworks that are built on top of servlets.
HTML form encoding types
There are three encoding HTML form methods for a POST request:
- application/x-www-form-urlencoded
- multipart/form-data
- text/plain
The application/x-www-form-urlencoded is the default encoding.
The values are encoded in key-value tuples separated by &. The =
character is used between the key and the value. Non-alphanumeric characters are
percent encoded. This encoding type is not suitable for binary files.
The multipart/form-data is used for non-ASCII data and binary files.
The input element's type attribute is set to
file.
The text/plain is used for debugging.
Java Servlet upload file example
In the following application, we have a web form to select a file to be uploaded to the server. The form calls a Java servlet, which reads the file and saves it into the directory.
Upload directory
Uploaded files must not be placed inside the web application directory. If the
web server serves uploaded scripts, an attacker could execute them. We use
/var/lib/zetcode/uploads, which is outside the web root.
$ sudo mkdir -p /var/lib/zetcode/uploads $ sudo chown "$USER" /var/lib/zetcode/uploads
The directory must be writable by the user who runs the servlet container. In production, use a dedicated directory with restrictive permissions.
Application
This is a Maven web application; it is deployed on embedded Jetty server.
pom.xml
src/main/
├── java/com/zetcode/web/
│ └── UploadFile.java
└── webapp/
└── index.html
This is the project structure.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zetcode</groupId>
<artifactId>JavaServletUploadFile</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>25</maven.compiler.release>
</properties>
<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.5.1</version>
</plugin>
<plugin>
<groupId>org.eclipse.jetty.ee11</groupId>
<artifactId>jetty-ee11-maven-plugin</artifactId>
<version>12.1.15</version>
</plugin>
</plugins>
</build>
</project>
This is the Maven POM file. The jakarta.servlet-api artifact is for
servlets.
The maven-war-plugin is responsible for collecting all artifact
dependencies, classes and resources of the web application and packaging them
into a web application archive (WAR). The jetty-ee11-maven-plugin
is a useful Maven plugin for rapid development and testing. It starts a Jetty
12.1 web server and deploys the application on the server.
package com.zetcode.web;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
@WebServlet(name = "UploadFile", urlPatterns = {"/UploadFile"},
initParams = { @WebInitParam(name = "uploadpath",
value = "/var/lib/zetcode/uploads") })
@MultipartConfig(
fileSizeThreshold = 1024 * 1024,
maxFileSize = 10 * 1024 * 1024,
maxRequestSize = 20 * 1024 * 1024
)
public class UploadFile extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
Part filePart = request.getPart("myfile");
if (filePart == null || filePart.getSubmittedFileName() == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
String submitted = filePart.getSubmittedFileName().replace('\\', '/');
String fileName = Path.of(submitted).getFileName().toString();
if (fileName.isBlank() || fileName.equals(".") || fileName.equals("..")) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
Path uploadDir = Path.of(getServletConfig().getInitParameter("uploadpath"))
.toAbsolutePath().normalize();
Files.createDirectories(uploadDir);
Path target = uploadDir.resolve(fileName).normalize();
if (!target.startsWith(uploadDir)) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
try (InputStream is = filePart.getInputStream()) {
Files.copy(is, target, StandardCopyOption.REPLACE_EXISTING);
}
response.setStatus(HttpServletResponse.SC_CREATED);
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("File successfully uploaded");
}
}
The UploadFile uploads a file to the
/var/lib/zetcode/uploads directory.
@WebServlet(name = "UploadFile", urlPatterns = {"/UploadFile"},
initParams = { @WebInitParam(name = "uploadpath",
value = "/var/lib/zetcode/uploads") })
With the @WebServlet annotation, we map the servlet to the
/UploadFile URL pattern and define an initial uploadpath variable.
@MultipartConfig(
fileSizeThreshold = 1024 * 1024,
maxFileSize = 10 * 1024 * 1024,
maxRequestSize = 20 * 1024 * 1024
)
The @MultipartConfig annotation indicates that the servlet expects
multipart/form-data requests. It also limits the size of a single
file and of the whole request, which prevents a client from exhausting server
memory or disk space.
Part filePart = request.getPart("myfile");
if (filePart == null || filePart.getSubmittedFileName() == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
The file part is retrieved with getPart(). If the form does not
contain the part, we return a 400 response.
String submitted = filePart.getSubmittedFileName().replace('\\', '/');
String fileName = Path.of(submitted).getFileName().toString();
if (fileName.isBlank() || fileName.equals(".") || fileName.equals("..")) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
We reduce the submitted name to a single file name. This strips any directory components from the client value before it is used.
Path uploadDir = Path.of(getServletConfig().getInitParameter("uploadpath"))
.toAbsolutePath().normalize();
Files.createDirectories(uploadDir);
Path target = uploadDir.resolve(fileName).normalize();
if (!target.startsWith(uploadDir)) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
We resolve the target file and verify that it stays inside the upload
directory. Without this check, a name containing .. could write
outside the directory.
try (InputStream is = filePart.getInputStream()) {
Files.copy(is, target, StandardCopyOption.REPLACE_EXISTING);
}
With Files.copy(), we copy the file to the destination directory.
The input stream is closed automatically.
response.setStatus(HttpServletResponse.SC_CREATED);
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("File successfully uploaded");
We return a 201 Created response and write a message with a
character writer.
<!DOCTYPE html>
<html>
<head>
<title>Uploading a file</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/purecss@2.0.3/build/pure-min.css"
integrity="sha384-cg6SkqEOCV1NbJoCu11+bm0NvBRc8IYLRGXkmNrqUBfTjmMYwNKPWBTIKyw9mHNJ"
crossorigin="anonymous">
<style>
main { margin:1em }
</style>
</head>
<body>
<main>
<form class="pure-form pure-form-stacked" method="post" action="UploadFile"
enctype="multipart/form-data">
<fieldset>
<legend>File:</legend>
<input type="file" name="myfile">
<button type="submit" class="pure-button pure-button-primary">Upload</button>
</fieldset>
</form>
</main>
</body>
</html>
This is the home page to select a file to be uploaded. It contains an HTML form. Upon
submitting the form, the processing is sent to the UploadFile.
<link rel="stylesheet" href="https://unpkg.com/purecss@2.0.3/build/pure-min.css"
integrity="sha384-cg6SkqEOCV1NbJoCu11+bm0NvBRc8IYLRGXkmNrqUBfTjmMYwNKPWBTIKyw9mHNJ"
crossorigin="anonymous">
We include the Pure.css library for creating responsible pages.
<form class="pure-form pure-form-stacked" method="post" action="UploadFile"
enctype="multipart/form-data">
The method attribute is post, because we send data to the server.
The action attribute specifies the name of the servlet, which
processes the request. The enctype attribute specifies the
multipart/form-data encoding type, which is required for uploading
a file with an HTML form.
<input type="file" name="myfile">
The type attribute of the input tag lets a user choose a
single file.
<button type="submit" class="pure-button pure-button-primary">Upload</button>
This is the Submit button.
In this article we have shown how to upload a single file with a Java servlet.
Verified output
A successful upload returns HTTP 201 and a short plain-text confirmation.
$ curl -i -F 'myfile=@sample.txt' localhost:8080/UploadFile HTTP/1.1 201 Created Server: Jetty(12.1.15) Content-Type: text/plain;charset=utf-8 Content-Length: 26 File successfully uploaded