In the beginning, we need to check if the request contains a multipart content using the isMultipartContent method found in the ServletFileUpload class from the library.

By default, Spring features a MultipartResolverthat we’ll need to disable to use this library. Otherwise, it’ll read the content of the request before it reaches our Controller.

We can achieve this by including this configuration in our application.properties file:

spring.http.multipart.enabled=false

Now, we can set the directory where our files are going to be saved, the threshold in which the library decides to write to disk and if files should be deleted after the request ends.

The library provides a DiskFileItemFactory class thattakes the responsibility of the configuration for the file saving and cleaning. The setRepository method sets the target directory, with the default being shown in the example.

Next, the setSizeThreshold sets a maximum file size.

Then, we have the setFileCleaningTracker method that, when set to null, leaves the temporary files untouched. By default, it deletes them after the request has finished.

Now we can continue to the actual file handling.

First, we create our ServletFileUpload by including our previously created factory; then we proceed to parse the request and generate a list of FileItem which are the main abstraction of the library for the form fields.

Now if we know it isn’t a normal form field, then we proceed to extract the InputStream and to call the useful copy method from IOUtils (for more options you can have a look at this tutorial).

Now we have our file stored in the necessary folder. This is usually a more convenient way to handle this situation as it allows easy access to the files, but also time/memory efficiency isn’t optimal.

In the next section, we’re going to take a look at the streaming API.

4. Streaming API

The streaming API is easy to use, making it a great way to process large files simply by not copying to a temporary location: