How to upload multiple files using Spring REST API

Introduction

Here in this tutorial I am going to tell 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

Eclipse 2020-06, At least Java 8, Gradle 6.5.1, Maven 3.6.3, Spring Boot 2.3.2

Set up project

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 Eclipse. 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'
	}
	
    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.

<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>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.2.RELEASE</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>

    <build>
        <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>at least 8</source>
					<target>at least 8</target>
				</configuration>
			</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 max size
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=10MB

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.

package com.roytuts.spring.rest.multiple.files.upload.rest.controller;

import java.io.InputStream;
import java.util.logging.Logger;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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;

@RestController
public class MultipleFileUploadRestController {

	private static final Logger logger = Logger.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.

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.

package com.roytuts.spring.rest.multiple.files.upload;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringRestMultipleFilesUploadApp {

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

}

Testing the Application

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: [email protected]
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: [email protected]
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: [email protected]
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: [email protected]
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

Thanks for reading.

Related posts

Leave a Comment