Spring WebFlux File Upload

Vinoth Selvaraj
3 min readApr 17, 2021

--

Spring WebFlux is a non-blocking web stack to handle multiple concurrent requests with minimal number of threads and scale with fewer hardware resources. It performs much better compared Spring MVC when the application has to handle a lot of I/O requests.

In this particular tutorial, We are going to take a look at multipart File Upload example with WebFlux.

Sample Application:

Lets consider a simple web application which requires users to upload files. Lets also consider different scenarios with the file upload.

  • single file
  • multiple files

Project Setup:

Create a Spring Boot project with below dependencies.

Spring WebFlux File Upload — Single File:

  • I first create a simple HTML file under resources/static directory which looks like this.
  • As part of submission, we send a POST request to upload/file/single endpoint.
  • Along with file, we can also send other information like user name.
  • HTML source is as shown here.
<div class="container mt-5">
<h1>Single File Upload Demo!</h1>
<form class="mt-3" action="upload/file/single" method="post" enctype="multipart/form-data">
<div class="form-group">
<label >User</label>
<input type="text" name="user-name"> <br/><br/>
<label >Single</label>
<input type="file" name="fileToUpload" id="fileToUpload1">
</div>
<div class="form-group mt-3">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
  • The back end controller is very simple. We look for the specific name field (in this case fileUpload & name field). We store the content on the server in a specific location.
  • When I run the application and upload the file, the file gets uploaded successfully on the server.

Spring WebFlux File Upload — Multiple Files:

  • If we expect the users of the application to upload multiple files, then the process is still same!! Instead of Mono, we need to use Flux.
<div class="container mt-5">
<h1>Multiple File Upload Demo!</h1>
<form class="mt-3" action="upload/file/multi" method="post" enctype="multipart/form-data">
<div class="form-group">
<label >Multi</label>
<input type="file" name="files" id="files" multiple>
</div>
<div class="form-group mt-3">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
  • Controller
  • When I tried to upload multiple files, I am able to receive them on the server side.

Summary:

We were able to successfully demonstrate Spring WebFlux File Upload.

You can learn more about Spring WebFlux.

The complete source code is here.

Happy coding :)

--

--

Vinoth Selvaraj
Vinoth Selvaraj

Written by Vinoth Selvaraj

Principal Software Engineer — passionate about software architectural design, microservices.

Responses (1)