Table of contents
1.
Introduction
2.
Multipart form data
3.
Using the Multipart/Form-Data to Upload Files to a Form
3.1.
Basic form
3.2.
Describe the upload action now:
3.3.
Testing the file upload
4.
Upload files directly
5.
Constructing together an HTTP multipart request to send the file to the web service endpoint.
6.
Cleaning up temporary files
7.
Frequently Asked Questions
7.1.
What is the purpose of Java's multipart file upload?
7.2.
What benefits can multipart uploads have?
7.3.
What is the biggest file that can be uploaded in a multipart upload?
7.4.
What is a Java uploader?
7.5.
When would a multipart be used?
8.
Conclusion
Last Updated: Jun 23, 2025
Easy

Java Developers-Handling File upload

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will understand Java developers-Handling file upload. There was a time when my applet needed to deliver some log files to some distant clients.

Introduction

Use an HTTP multipart request to implement this file upload feature when your applet loads in the browser of the remote client. For my applet to be able to read log files and send them back to a web server that will collect the log files, policies have to be in place.

This post explains sending a Java HTTP multipart request to upload a file without utilising additional libraries. Now we understand Java developers-Handling file upload.

Multipart form data

 The <form> tag enctype attribute specifies the encoding scheme for the form data. One of the two methods for encoding the HTML form is this one. It is utilised primarily when an HTML form calls for file uploading. Due to the enormous file size, it sends the form data to the server in segments.

Multipart form data

Using the Multipart/Form-Data to Upload Files to a Form

For Java developers-Handling file upload is the most important part of making a website dynamic and interactive. Using a form with a particular multipart/form-data encoding, which enables you to combine regular form data with file attachment data, is the standard method for uploading files in online applications.

Form-Data to Upload Files to a Form

 

Note: POST must be used as the HTTP method when submitting the form (not GET).

POST Method: Via a separate communication with the processing script, the data is transmitted to the server using the POST method as a package. The POST technique will not display any data in the URL. Now we make a basic form in Java developers-Handling file upload.

POST Method:

Basic form

@helper.form(action = routes.HomeController.upload, Symbol("enctype") -> "multipart/form-data") {

    <input type="file" name="picture">

    <p>
        <input type="Click Here to Upload">
    </p>
}

Describe the upload action now:

import play.mvc.Result;
import play.libs.Files.TemporaryFile;
import play.mvc.Http;
import play.mvc.Controller;
import Java.nio.file.Paths;

public class HomeController extends Controller {
public Result upload(Http.Request request) {
      Http.MultipartFormData<TemporaryFile> body = request.body().asMultipartFormData();
      Http.MultipartFormData.FilePart<TemporaryFile> picture = body. getFile("picture");
  if (picture != null) {
  String fileName = picture. getFilename();
  long fileSize = picture. getFileSize();
  String contentType = picture. getContentType();
  TemporaryFile file = picture. getRef();
  file.copyTo(Paths.get("/tmp/picture/destination.jpg"), true);
      return ok("File uploaded");
         }
      else {
      return badRequest().flashing("error", "Missing file");
              }
        }
}

 

You can obtain a reference to a temporary file using the getRef() method. Play typically handles file uploads in this manner.

Add a POST route as a final step:

POST  /          controllers.HomeController.upload(request: Request)

 

Note: An empty file will be treated just like it never existed. The same rule applies even though the file itself would not empty if the filename header of a multipart/form-data file upload part is empty.

Testing the file upload

Creating an automated JUnit test for your upload action is another option:

Testing the file upload

The RequestBuilder method bodyMultipart requires an Http.MultipartFormData.FilePart, so that's what we're doing. The rest is identical to controllers used for unit testing.

Upload files directly

Using Ajax to upload files asynchronously from a form is another technique to communicate files to the server. In this scenario, the request body will simply contain the contents of the file without being encoded as multipart/form-data.

public Result upload(Http.Request request) {
  File file = request.body().asRaw().asFile();
  return ok("File uploaded");
}

 

Instead of sending the ByteString from the Accumulator into a temporary file object, the akka.stream.Javadsl.FileIO class is used to build a sink that sends the ByteString into a Java.io.File object.

A running total of the uploaded bytes can be delivered somewhere else in the system by using a custom file part handler, which also allows behaviour to be injected.

Constructing together an HTTP multipart request to send the file to the web service endpoint.

Fiddler's output makes it simple for your Java programme to send an HTTP multipart request. We make use of the following classes that are part of the Java standard library to avoid utilising other libraries:

java libraries

Cleaning up temporary files

As we have understood, Java developers-Handling file uploads now we move into deletion of the stored file. Files are stored on a temporary filesystem that is available via the getRef() method when uploading files using the TemporaryFile API. The TemporaryFileCreator trait is the source of all TemporaryFile references, and the implementation can be changed as needed. Additionally, a new atomicMoveWithFallback method uses StandardCopyOption.ATOMIC MOVE when it is available.

Cleaning up temporary files

The idea behind TemporaryFile is that it is only in scope upon completion and should be moved out of the temporary file system as soon as possible. Uploading files is an inherently risky process because an unbounded file upload can result in the filesystem filling up. No longer needed temporary files are removed.

The reaper is disabled by default and is enabled through the configuration of the application.conf:

play.temporaryFile {
  reaper {
    enabled = true
    initialDelay = "5 minutes"
    interval = "30 seconds"
    olderThan = "30 minutes"
  }
}

 

Using the "olderThan" attribute, the configuration above will delete files that are older than 30 minutes. Five minutes after the application launches, the reaper will begin, and over the following 30 seconds, it will inspect the filesystem. Protracted file uploads could run into the reaper if the system is not carefully designed because it is unaware of any current file uploads.

Frequently Asked Questions

What is the purpose of Java's multipart file upload?

Using a form with a particular multipart/form-data encoding, which enables you to combine regular form data with file attachment data, is the standard method for uploading files in online applications. Note: POST must be used as the HTTP method when submitting the form (not GET ).

What benefits can multipart uploads have?

The benefits of using multipart upload are as follows: Throughput can be increased by uploading portions simultaneously. A smaller portion size reduces the burden of resuming a failed upload due to a network error, allowing for quick recovery from any network problems.

What is the biggest file that can be uploaded in a multipart upload?

The lowest and maximum part sizes permitted are 1 MB and 4 GB, respectively. Except for the final part, all of the parts you post using this upload ID must be the same size. The final one can be smaller or the same size.

What is a Java uploader?

Users of Internet Explorer browsers can upload a folder together with all of its contents using the Java Uploader Tool. Users are able to upload folders up to 10 GB in size using the Java Uploader utility. Note that neither Google Chrome nor Firefox supports this plugin.

When would a multipart be used?

One or more sets of data are combined into one body of a multipart request and are separated by boundaries. Usually, these requests are used for file uploads and for transmitting multiple types of data in a single request (for example, a file along with a JSON object).

Conclusion

In this blog, we have gone through Java developers-Handling file upload with deletion of temporary files, using the Multipart/Form-Data to upload files to a form. Also understood how to upload the file directly.

you may also check File upload with multer.

If you face any doubt, please comment, and we will love to answer your questions.

Want expertise in the Basics of Java with Data Structures and Algorithms? Check out our course.
 

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass