Last updated on March 9th, 2024
In this application, we can upload a file through Spring Boot Rest API for this we are using MultipartFile Interface.
MultipartFile: A representation of an uploaded file received in the multipart request.
The file contents are either saved in the memory or temporarily on a disk. In either case, the user is responsible for copying the file contents to a session-level or persistent store as and if desired. The temporary storage will be removed at the end of the request processing.
Development Process:
1. Keep eclipse IDE ready(STS Integrated)
2. Create a Spring Boot Starter Project
3. Enables Multipart File configuration in the application.properties file
4. Create a FileStorage class
5. Create a Service
6. Create a Controller class
7. Run the Project
1. Keep eclipse IDE ready(STS Integrated)
Refer to this article How to Create Spring Project in IDE to create Spring Boot Project in Eclipse IDE.
2. Create a Spring Boot Starter Project
Add the following dependencies:
• Spring Web
• Spring Configuration Processor
Maven Dependency
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>Upload_File_Spring_Boot_Rest_Api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Upload_File_Spring_Boot_Rest_Api</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3. Enables Multipart File configuration in the application.properties file
## MULTIPART (MultipartProperties)
# Enable multipart uploads
spring.servlet.multipart.enabled=true
# Threshold after which the files are written to a disk.
spring.servlet.multipart.file-size-threshold=2KB
# Max file size.
spring.servlet.multipart.max-file-size=500KB
# Max Request Size
spring.servlet.multipart.max-request-size=500KB
## File Storage Properties
file.upload-dir=./uploads
server.port=8081
4. Create a FileStorage class
FileStorageProperties.java
package com.example.property;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "file")
public class FileStorageProperties {
private String uploadDir;
public String getUploadDir() {
return uploadDir;
}
public void setUploadDir(String uploadDir) {
this.uploadDir = uploadDir;
}
}
→ @ConfigurationProperties allows mapping the entire Properties and Yaml files into a java class object. By default, this annotation reads values from the application.properties file.
5. Create a Service
FileUploadService.java
package com.example.service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import com.example.property.FileStorageProperties;
@Service
public class FileUploadService {
private final Path fileUploadLocation;
@Autowired
public FileUploadService(FileStorageProperties fileStorageProperties) {
this.fileUploadLocation = Paths.get(fileStorageProperties.getUploadDir())
.toAbsolutePath().normalize();
try {
Files.createDirectories(this.fileUploadLocation);
} catch (Exception e) {
throw new RuntimeException("Cannot create the directory where you want to the uploaded the files will be kept.", e);
}
}
public String uploadFile(MultipartFile file) {
// Renormalize the file name
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
// Verify if the file's name is containing invalid characters
if (fileName.contains("..")) {
throw new RuntimeException("Sorry! File name is containing invalid path sequence " + fileName);
}
// Copy file to the target path (replacing existing file with the same name)
Path targetLocation = this.fileUploadLocation.resolve(fileName);
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
return fileName;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
6. Create a Controller class
UploadController.java
package com.example.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.example.service.FileUploadService;
@RestController
public class UploadController {
@Autowired
private FileUploadService fileUploadService;
@PostMapping("/uploadFile")
public String uploadFile(@RequestParam("file") MultipartFile file) {
String fileName = fileUploadService.uploadFile(file);
ServletUriComponentsBuilder.fromCurrentContextPath().path(fileName).toUriString();
return "Upload Successfully";
}
}
7. Run the Project
Right Click on this project’s UploadFileSpringBootRestApiApplication.java class then clicks on Run As Java Application. Thus you see console output and your application is started successfully.
Go to the postman and type this URL http://localhost:8081/uploadFile(POST type method)
Conclusion:
This example explains How to upload the file using Spring Boot Rest API? How to enable MultipartFile configuration in the application.properties?