Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

1. Overview

Spring WebFlux is a reactive web framework that provides a non-blocking event loop to handle I/O operations asynchronously. Also, it uses Mono and Flux reactive stream publishers to emit data when subscribed to.

This reactive approach helps applications handle large volumes of requests and data without allocating huge resources.

In this tutorial, we’ll learn how to upload multiple files to a directory using Spring WebFlux through a step-by-step guide. Also, we’ll map the filename to an entity class for easy retrieval.

2. Project Setup

Let’s create a simple reactive Spring Boot project that uploads multiple files to a directory. For simplicity, we’ll use the root directory of our project to store the files. In production, we can use a file system like AWS S3, Azure Blob Storage, Oracle Cloud Infrastructure storage, etc.

2.1. Maven Dependencies

To begin with, let’s bootstrap a Spring WebFlux application by adding the spring-boot-starter-webflux dependency to the pom.xml:

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

This provides the core Spring WebFlux APIs and embedded Netty server to build reactive web applications.

Also, let’s add the spring-boot-starter-data-r2dbc and H2 database dependencies to the pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-r2dbc</artifactId>
    <version>3.2.0</version>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>2.2.224</version>
</dependency>

Spring WebFlux R2DBC is a reactive database connector and the H2 database is an in-memory database.

Finally, let’s add the R2DBC native driver dependency to the pom.xml:

<dependency>
    <groupId>io.r2dbc</groupId>
    <artifactId>r2dbc-h2</artifactId>
    <version>1.0.0.RELEASE</version>
</dependency>

This native driver is implemented for the H2 database.

2.2. Entity, Repository and Controller

Let’s create an entity class named FileRecord:

class FileRecord {
    @Id
    private int id;
    private List<String> filenames;
    
   // standard getters, setters, constructor  
}

Next, let’s create a repository named FileRecordRepository:

@Repository
interface FileRecordRepository extends R2dbcRepository<FileRecord, Integer> {
}

Finally, let’s create a controller class:

@RestController
class FileRecordController {
}

In the subsequent sections, we’ll map our file name and its extension to the fileName field.

3. Uploading Files to a Directory

Occasionally, we may upload multiple files to a filesystem without mapping the filenames to database entities. In this case, retrieving the files later may be challenging.

Let’s see an example code that uploads multiple files to our root directory without mapping the file name to an entity:

PostMapping("/upload-files")
Mono uploadFileWithoutEntity(@RequestPart("files") Flux<FilePart> filePartFlux) {
    return filePartFlux.flatMap(file -> file.transferTo(Paths.get(file.filename())))
      .then(Mono.just("OK"))
      .onErrorResume(error -> Mono.just("Error uploading files"));
}

First, we create a method named uploadFileWithoutEntity() which accepts Flux of FilePart objects. Then, we invoke the flatMap() method on each FilePart object to transfer the file and return a Mono. This creates a separate Mono for each file transfer operation and flattens the stream of Monos into a single Mono.

Let’s test the endpoint by uploading multiple files through Postman:

Upload multiple files and do not map to database entity

In the image above, we upload three files to the project root directory. The endpoint returns OK to show that the operation was completed successfully.

Notably, we use the onErrorResume() method to handle errors related to file upload explicitly. In a case where failure occurs while uploading, the endpoint returns the error message.

However, files uploaded earlier may have been transferred successfully before the failure. In this case, clean-up may be needed to delete partially uploaded files on error. For simplicity, we didn’t cover the clean-up process.

4. Mapping Uploaded Files to Database Entities

Furthermore, we can map the file name to the database entity. This gives us the flexibility to retrieve files by their Id later. This is useful when we want to display an image or perform further computation.

4.1. Database Configuration

First, let’s create a schema.sql file in the resource folder to define the database table structure:

CREATE TABLE IF NOT EXISTS file_record (
    id INT NOT NULL AUTO_INCREMENT,
    filenames VARCHAR(255),
    PRIMARY KEY (id)
);

Here, we create a file record table to store the uploaded file name and its extension. Next, let’s write a configuration to initialize the schema on startup:

@Bean
ConnectionFactoryInitializer initializer(ConnectionFactory connectionFactory) {
    ConnectionFactoryInitializer initializer = new ConnectionFactoryInitializer();
    initializer.setConnectionFactory(connectionFactory);
    initializer.setDatabasePopulator(new ResourceDatabasePopulator(new ClassPathResource("schema.sql")));

    return initializer;
}

Also, let’s define the database URL in the application.properties file:

spring.r2dbc.url=r2dbc:h2:file:///./testdb

Here, we define the R2DBC URL to connect to the H2 database. For simplicity, the database isn’t protected with a password.

4.2. Service Layer

First, let’s create a service class and add the logic to handle data persistence:

@Service
public class FileRecordService {

    private FileRecordRepository fileRecordRepository;

    public FileRecordService(FileRecordRepository fileRecordRepository) {
        this.fileRecordRepository = fileRecordRepository;
    }

    public Mono<FileRecord> save(FileRecord fileRecord) {
        return fileRecordRepository.save(fileRecord);
    }
}

Here, we inject the FileRecordRepository interface in the service class and define the logic to save the file name and its extension in the database.

Next, let’s inject the FileRecordService class into the controller class:

private FileRecordService fileRecordService;

public FileRecordController(FileRecordService fileRecordService) {
    this.fileRecordService = fileRecordService;
}

The code above makes the logic to persist data available in the controller class.

4.3. Upload Endpoint

Finally, let’s write an endpoint that uploads multiple files to the root directory and maps the file names and their extension to an entity class:

@PostMapping("/upload-files-entity")
Mono uploadFileWithEntity(@RequestPart("files") Flux<FilePart> filePartFlux) {
    FileRecord fileRecord = new FileRecord();

    return filePartFlux.flatMap(filePart -> filePart.transferTo(Paths.get(filePart.filename()))
      .then(Mono.just(filePart.filename())))
      .collectList()
      .flatMap(filenames -> {
          fileRecord.setFilenames(filenames);
          return fileRecordService.save(fileRecord);
      })
      .onErrorResume(error -> Mono.error(error));
}

Here, we create an endpoint that emits Mono. It accepts Flux of FilePart and uploads each file. Next, it collects the file name and its extension and maps them to the FileRecord entity.

Let’s test the endpoint with Postman:

Upload multiple files and map to database entity

 

Here, we upload two files named spring-config.xml and server_name.png to the server. The POST request emits a Mono showing details of the request.

For simplicity, we didn’t validate the file name, type, and size.

4.4. Retrieve Book by Id

Let’s implement an endpoint to retrieve stored a file record by its Id to view the associated file names.

First, let’s add the logic to retrieve a file record by its Id to the service class:

Mono findById(int id) {
    return fileRecordRepository.findById(id);
}

Here, we invoke the findById() on bookRepository to retrieve the store Book by its id.

Next, let’s write an endpoint to retrieve the file record:

@GetMapping("/files/{id}")
Mono geFilesById(@PathVariable("id") int id) {
    return fileRecordService.findById(id)
      .onErrorResume(error -> Mono.error(error));
}

This endpoint returns a Mono containing the file Id and file name.

Let’s see the endpoint in action using Postman:

get associated files by it id

The image above shows the return file information. The image file URLs can be returned in the API response. The client can use these URLs to retrieve and display the images. Additional processing and editing of the images can be implemented by passing the files through processing services.

5. Conclusion

In this article, we learned how to upload multiple files to the server file system using Spring WebFlux.  Also, we saw how to upload files with or without mapping the file name and extension to a database entity.

Finally, we saw an approach that uploads the files and persists the file name and its extension to the database.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat = Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Microsoft – NPI (cat=Spring)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

eBook Jackson – NPI EA – 3 (cat = Jackson)