Spring Boot
Multipart Upload
JSON
DTO
Controller

Spring Boot controller - Upload Multipart and JSON to DTO

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Spring Boot is a powerful framework that is built on top of the Spring Framework. It simplifies the process of configuring and deploying spring applications by providing a wide array of default configurations that save developers from redundant setup work. One common task in web applications is handling file uploads and combining them with other form data (such as JSON) in a type-safe manner. This article will delve into how to effectively manage multipart file uploads along with JSON data, and map them directly to a Data Transfer Object (DTO) using a Spring Boot controller.

Understanding Multipart and JSON Payloads

In a typical web application, users might need to upload files along with some metadata or accompanying data in the form of JSON. This combined data structure enhances the complexity in handling HTTP requests since they are of different content types, namely multipart/form-data and application/json.

Setting up a Spring Boot Project

Before proceeding, ensure that your Spring Boot project is set up correctly. You will need the spring-boot-starter-web dependency added to your pom.xml for Maven or build.gradle for Gradle.

xml
1<!-- Maven -->
2<dependency>
3    <groupId>org.springframework.boot</groupId>
4    <artifactId>spring-boot-starter-web</artifactId>
5</dependency>
groovy
// Gradle
implementation 'org.springframework.boot:spring-boot-starter-web'

Configuring Multipart Handling

To enable multipart file handling, you need to include the spring-boot-starter-web dependency and ensure multipart is enabled in your application.properties.

properties
spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MB

Creating a DTO Class

Define a Data Transfer Object (DTO) class to handle the binding of incoming data. This class will contain fields corresponding to the JSON data and a MultipartFile for receiving the file.

java
1public class UploadDTO {
2
3    private String name;
4    private String description;
5    private MultipartFile file;
6
7    // Getters and Setters
8    public String getName() {
9        return name;
10    }
11    
12    public void setName(String name) {
13        this.name = name;
14    }
15    
16    public String getDescription() {
17        return description;
18    }
19    
20    public void setDescription(String description) {
21        this.description = description;
22    }
23    
24    public MultipartFile getFile() {
25        return file;
26    }
27    
28    public void setFile(MultipartFile file) {
29        this.file = file;
30    }
31}

Implementing the Controller

The controller needs to handle both the multipart file and JSON data. This can be done using the @RequestPart annotation to handle parts of the request separately.

java
1@RestController
2@RequestMapping("/api")
3public class UploadController {
4
5    @PostMapping("/upload")
6    public ResponseEntity<String> handleFileUpload(
7            @RequestPart("file") MultipartFile file,
8            @RequestPart("data") String data) throws IOException {
9        
10        ObjectMapper objectMapper = new ObjectMapper();
11        UploadDTO uploadDTO = objectMapper.readValue(data, UploadDTO.class);
12        uploadDTO.setFile(file);
13
14        // Process uploaded data here
15        // Example: save file to disk, validate data, etc.
16
17        return ResponseEntity.ok("File uploaded and processed successfully!");
18    }
19}

Summary of Key Points

The table below summarizes the key components and configuration needed:

ComponentDescription
Dependencyspring-boot-starter-web to enable multipart support
Property ConfigMultipart settings in application.properties
DTO ClassCombines JSON fields and MultipartFile
Controller MethodHandles @RequestPart for file and JSON data
JSON HandlingUse ObjectMapper to parse JSON data into DTO

Additional Notes

  • Validation: Consider adding validation annotations (e.g., @NotNull, @Size) to your DTO for input validation.
  • Exception Handling: Implement global or controller-specific exception handlers using Spring's @ExceptionHandler or @ControllerAdvice to manage any potential errors during the upload process.
  • Security: Implement necessary security measures to avoid vulnerabilities such as file uploads leading to path traversal attacks.
  • Testing: Thoroughly test the controller using integration tests to ensure the multipart handling and JSON parsing function as expected.

Conclusion

Handling multipart and JSON uploads within a Spring Boot application can be managed efficiently using DTOs and the appropriate Spring annotations. By setting up the environment correctly and following best practices, developers can streamline complex upload processes, allowing for robust and scalable web applications.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.