Steps To Upload Multiple Files Using WebFlux

To Upload Multiple Files Using WebFlux, here we created a Spring Boot project which is maven type. For this project, we use the below dependencies.

Project Dependencies:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>


Project Folder:


Step 1: Main Class

Once the project is created automatically Spring framework creates this class with the main function and Spring application execution starts from here only.

ProjectApplication.java:

Java
package com.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class UploadfilesApplication {

    public static void main(String[] args) {
        SpringApplication.run(UploadfilesApplication.class, args);
    }

}


Step 2: Create a Service Class

We created a Service class by using @Service annotation with the name FileStorageService in the main package of the project.

  • This class is used for define the business logic for uploading files into a given file path in this class.
  • In this class, first write the logic for if a folder exists or not, If not we create a folder with a given name.
  • After this, we created a method called saveFile() which can be a void-type mono publisher Here we use FilePart to save the files.

FileStorageService.java:

Java
package com.app;

import org.springframework.http.codec.multipart.FilePart;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class FileStorageService {

    private static final String UPLOAD_DIR = "uploads/";

    public FileStorageService() {
        try {
            Files.createDirectories(Paths.get(UPLOAD_DIR));
        } catch (Exception e) {
            throw new RuntimeException("Could not create upload directory!", e);
        }
    }

    public Mono<Void> saveFile(FilePart filePart) {
        Path path = Paths.get(UPLOAD_DIR + filePart.filename());
        return filePart.transferTo(path);
    }
}


Step 3: Create Controller

We created a RestController class by using @RestController annotation with the name FileUploadController in the main package of the project.

  • This class is used to define the API endpoints which is used for uploading files by using this API.
  • In this controller class, first we autowired the FileStorageService to access the saveFile() method.
  • Here we use Flux<FilePart> because we upload more than one file or file at a time that’s why Flux is a suitable publisher for this.
  • Now we created a POST mapping API endpoint to upload files, and it can return a response in the form of a Response Entity object.

FileUploadController.java:

Java
package com.app;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @Autowired
    private FileStorageService fileStorageService;

    @PostMapping(value = "/files", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Mono<ResponseEntity<String>> uploadFiles(@RequestPart("files") Flux<FilePart> files) {
        return files.flatMap(fileStorageService::saveFile)
                    .then(Mono.just(ResponseEntity.ok("Files successfully uploaded!")));
    }
}


Step 4: Run the Application

Once project development is completed with the required logic, now run this project as Spring Boot App or we can run this project by using Maven commends also. Here, run this project as a Spring Boot App. This Project runs on an 8080 port number with Netty server by default.


Step 5: Testing API

Now test the API endpoint. Here we use the Postman tool for testing the API endpoint.

API Testing:

  • Open Postman
  • Click on the New button and select HTTP Request
  • Set the request method to POST.
  • Enter the URL for your API endpoint. http://localhost:8080/upload/files.
  • Go to the “Body” tab.
  • Select form-data.
  • Add multiple files by clicking on the “Key” field and entering files.
  • For each file you want to upload, click on the “Choose Files” button in the “Value” field and select the file from your file system.
  • Ensure the key is files for each file entry.
  • Click on the Send button to submit the request



Now, go to your project folder, there is a new folder is visible to you with the name upload. In that folder, uploaded files are saved. While testing this API, we got the below result.




Upload Multiple Files Using WebFlux

Spring WebFlux is a framework of the Spring ecosystem designed to build responsive web applications. It provides support for non-blocking, asynchronous programming with reactive streams, and makes it ideally suited to efficiently handle large numbers of concurrent connections You must use the Spring WebFlux module to upload multiple files to WebFlux with use it in a Spring Boot application Below is a step-by-step -step guide to create a simple application.

In this article, we will use RestTemplate to create API endpoints using POST Mapping. FilePart is an interface in Spring WebFlux that represents a part of multipart/form-data requests used primarily for processing file access. It is part of the org.springframework.http.codec.multipart package. When a client sends a file using a multipart/form-data query, each file is represented as a FilePart on the server side.

Key Features of FilePart:

  • Non-blocking I/O: FilePart functions are non-blocking and can be used in reactive programming models, taking advantage of asynchronous I/O.
  • File Metadata: Provides methods to retrieve file metadata such as the filename.
  • File Content: Allows access to the file’s content as a reactive stream.
  • File Storage: Provides methods to transfer the file to a location on the server, making it easy to save the uploaded files.

Similar Reads

Steps To Upload Multiple Files Using WebFlux

To Upload Multiple Files Using WebFlux, here we created a Spring Boot project which is maven type. For this project, we use the below dependencies....