How To Upload Multiple Files Using Spring REST API

Multiple Files Upload

Here in this tutorial I am going to show you how to upload multiple files using Spring Boot REST API. I had also shown you in my another example how to upload single file using Spring Boot REST API framework.

For uploading file(s) you can use any client, for example, browser or any REST client (Postman) that supports for uploading of files. Even you can write client side code using HTML, CSS jQuery/JavaScript or React JS, Angular etc. to upload multiple files.

Here for this example, I am using Postman tool to upload multiple files. While you are selecting files make sure you hold Ctrl key (Windows OS) for selecting multiple files. Once you are done with file selection then you can hit the Send button for uploadin files on server.

Prerequisites

Java 8/19, Maven 3.6.3/3.8.5, Spring Boot 2.3.2/2.4.5/3.1.0

Project Setup

As a prerequisite you have to first setup the project environment so that you would be able to write the required code for uploading file into server and process the file data for your application’s need.

You can create either gradle or maven based project in your favorite IDE or tool. If you are creating gradle based project then you can use build.gradle script to add the required dependencies into the project. I have also specified the JDK version I will be using for this application.

buildscript {
	ext {
		springBootVersion = '2.3.2.RELEASE' to '2.4.5'
	}
	
    repositories {
    	mavenCentral()
    }
    
    dependencies {
    	classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

plugins {
    id 'java-library'
    id 'org.springframework.boot' version "${springBootVersion}"
}

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    mavenCentral()
}

dependencies {
	implementation "org.springframework.boot:spring-boot-starter-web:${springBootVersion}"
}

If you are creating maven based project then you can use below pom.xml file.

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.roytuts</groupId>
	<artifactId>spring-rest-multiple-files-upload</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>19</maven.compiler.source>
		<maven.compiler.target>19</maven.compiler.target>
	</properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.1.0</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

application.properties

If you need to restrict the size of file or files then you can do so using application.properties file which is kept under classpath folder src/main/resources.

The default file upload size is 2MB. So you can override the maximum file size that can be uploaded into server using the application.properties file using the below configuration values.

For example, to upload file size up to 10MB you can set up the following configurations.

#multipart config
spring.http.multipart.file-size-threshold=2MB
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=10MB

The same configuration can be done using annotation on class level using the following syntax:

@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2 MB
		maxFileSize = 1024 * 1024 * 10, // 10 MB
		maxRequestSize = 1024 * 1024 * 10)
public class MultipleFileUploadRestController {
...

Multiple File Upload – Spring REST Controller

Now I will create a Spring REST controller class to implement the functionality for allowing multiple files upload.

I have the below method with http method POST request and request files parameter multiplefiles, which will be used for uploading multiple files from client.

I use the data type as MultipartFile to upload the file(multipart/form-data). Notice for multiple files I am using array of MultipartFile object as a RequestBody parameter.

In the controller method you need to check whether at least one file has been uploaded or not and if uploaded then you need to extract the file information and do further processing for your application according to the business. I am using Java’s built-in logger API just to print the file information.

@RestController
public class MultipleFileUploadRestController {

	private static final Logger logger = LoggerFactory.getLogger(MultipleFileUploadRestController.class.getName());

	@PostMapping("/upload/multiple/files")
	public ResponseEntity<String> uploadData(@RequestParam("multipleFiles") MultipartFile[] files) throws Exception {

		if (files == null || files.length == 0) {
			throw new RuntimeException("You must select at least one file for uploading");
		}

		StringBuilder sb = new StringBuilder(files.length);

		for (int i = 0; i < files.length; i++) {
			InputStream inputStream = files[i].getInputStream();
			String originalName = files[i].getOriginalFilename();
			String name = files[i].getName();
			String contentType = files[i].getContentType();
			long size = files[i].getSize();

			sb.append("File Name: " + originalName + "\n");

			logger.info("InputStream: " + inputStream);
			logger.info("OriginalName: " + originalName);
			logger.info("Name: " + name);
			logger.info("ContentType: " + contentType);
			logger.info("Size: " + size);
		}

		// Do processing with uploaded file data in Service layer
		return new ResponseEntity<String>(sb.toString(), HttpStatus.OK);
	}

}

Finally I am sending all file names in the response of the client. In real world application, ideally you would process all files’ data in Service layer code after receiving files but here I have just shown the idea how to upload multiple files using Spring REST service.

Even you can use List instead of array as an argument for MultipartFile for uploading multiple files, for example, the below code may help you:

@PostMapping("/upload/multiple/files2")
public ResponseEntity<String> uploadMultipleFiles(@RequestParam("multipleFiles") List<MultipartFile> files)
		throws Exception {

	if (files == null || files.isEmpty()) {
		throw new RuntimeException("You must select at least one file for uploading");
	}

	StringBuilder sb = new StringBuilder(files.size());

	for (int i = 0; i < files.size(); i++) {
		InputStream inputStream = files.get(i).getInputStream();
		String originalName = files.get(i).getOriginalFilename();
		String name = files.get(i).getName();
		String contentType = files.get(i).getContentType();

		sb.append("File Name: " + originalName + "\n");

		logger.info("InputStream: " + inputStream);
		logger.info("OriginalName: " + originalName);
		logger.info("Name: " + name);
		logger.info("ContentType: " + contentType);
		logger.info("Size: " + files.size());
	}

	// Do processing with uploaded file data in Service layer
	return new ResponseEntity<String>(sb.toString(), HttpStatus.OK);
}

Spring Boot Main Class

You need to create a Spring Boot main class in order to see the file upload example using Spring REST Controller in action. This main class deploys the application in embedded Tomcat server and runs on port 8080.

@SpringBootApplication
public class SpringRestMultipleFilesUploadApp {

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

}

Testing Multiple Files Upload

Now once your application is deployed into Tomcat server by running the main class, you need to open Postman or any other REST client that supports file upload functionality.

Using the tool you can do the following configurations to send multiple files into server.

multiple files upload using spring rest api

Console Output

f.u.r.c.MultipleFileUploadRestController : InputStream: java.io.FileInputStream@27dd10bc
f.u.r.c.MultipleFileUploadRestController : OriginalName: WishNet.txt
f.u.r.c.MultipleFileUploadRestController : Name: multipleFiles
f.u.r.c.MultipleFileUploadRestController : ContentType: text/plain
f.u.r.c.MultipleFileUploadRestController : Size: 77
f.u.r.c.MultipleFileUploadRestController : InputStream: java.io.FileInputStream@4de82fe9
f.u.r.c.MultipleFileUploadRestController : OriginalName: user.sql
f.u.r.c.MultipleFileUploadRestController : Name: multipleFiles
f.u.r.c.MultipleFileUploadRestController : ContentType: application/x-sql
f.u.r.c.MultipleFileUploadRestController : Size: 1801
f.u.r.c.MultipleFileUploadRestController : InputStream: java.io.FileInputStream@31564540
f.u.r.c.MultipleFileUploadRestController : OriginalName: sql-changelog-alter-table.sql
f.u.r.c.MultipleFileUploadRestController : Name: multipleFiles
f.u.r.c.MultipleFileUploadRestController : ContentType: application/x-sql
f.u.r.c.MultipleFileUploadRestController : Size: 4318
f.u.r.c.MultipleFileUploadRestController : InputStream: java.io.FileInputStream@3d5a7346
f.u.r.c.MultipleFileUploadRestController : OriginalName: soumitra.jpg
f.u.r.c.MultipleFileUploadRestController : Name: multipleFiles
f.u.r.c.MultipleFileUploadRestController : ContentType: image/jpeg
f.u.r.c.MultipleFileUploadRestController : Size: 47549

That’s all. Hope you got an idea on how to upload multiple file using Spring REST API.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *