Spring Boot Upload File Example (2024)
In this tutorial, we'll show you how to upload file in Spring Boot application with following rest endpoints.
POST
method to Upload file usingMultipartFile[] file
as a parameter.GET
method to list all files from the file storage folder.
Create Spring Boot Project from Spring Initializer site https://start.spring.io/
Project Structure
Maven Dependency
All we need is spring-boot-starter-web
dependency in pom.xml, add org.projectlombok
for auto generating getters/setters/constructor.
<?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.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.techgeeknext</groupId>
<artifactId>spring-boot-upload-file-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-upload-file-example</name>
<description>Spring Boot upload file</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Constant File
Create File Utility class, for keeping constant variables:
package com.techgeeknext.util;
import java.nio.file.Path;
import java.nio.file.Paths;
public final class FileUtil {
private FileUtil() {
// restrict instantiation
}
public static final String folderPath = "incoming-files//";
public static final Path filePath = Paths.get(folderPath);
}
RestController to upload file
Create RestController class and define below rest endpoint:
POST
method to Upload file usingMultipartFile[] file
as a parameter.GET
method to list all files from the file storage folder.
package com.techgeeknext.controller;
import com.techgeeknext.util.FileUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
@Controller
//@CrossOrigin(origins = "http://localhost:8082") open for specific port
@CrossOrigin() // open for all ports
public class FileUploadController {
/**
* Method to upload file
*
* @param file
* @return
*/
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
try {
createDirIfNotExist();
byte[] bytes = new byte[0];
bytes = file.getBytes();
Files.write(Paths.get(FileUtil.folderPath + file.getOriginalFilename()), bytes);
return ResponseEntity.status(HttpStatus.OK)
.body("Files uploaded successfully: " + file.getOriginalFilename());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED)
.body("Exception occurred for: " + file.getOriginalFilename() + "!");
}
}
/**
* Create directory to save files, if not exist
*/
private void createDirIfNotExist() {
//create directory to save the files
File directory = new File(FileUtil.folderPath);
if (!directory.exists()) {
directory.mkdir();
}
}
/**
* Method to get the list of files from the file storage folder.
*
* @return file
*/
@GetMapping("/files")
public ResponseEntity<String[]> getListFiles() {
return ResponseEntity.status(HttpStatus.OK)
.body(new java.io.File(FileUtil.folderPath).list());
}
}
Spring Boot Main Application
Start the Spring main application:
package com.techgeeknext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootUploadFileApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootUploadFileApplication.class, args);
}
}
Test Upload File Example
POST - Upload file
Open POSTMAN and select the value to upload the file by using http://localhost:8282/upload?file request.GET - List of uploaded files
Open POSTMAN and get the list of uploaded file names by using http://localhost:8282/files request.
Download Source Code
The full source code for this article can be found on below.Download it here - Spring Boot Upload File Example