File Upload Example using Spring REST Controller

Introduction

File upload example using Spring REST Controller will show you how to upload a file when selected for uploading from any client (browser or any client) and Spring REST service is used as a server side technology for uploading the file. The file may be any type, i.e., such as excel, text, word, pdf etc. HereIe will create Spring Boot application as it reduces the most of the efforts in project configurations.

Related Posts:

Prerequisites

Java at least 8, Gradle 6.1.1 – 6.7.1, Maven 3.6.3, Spring Boot 2.2.5 – 2.4.3

Project Setup

As a prerequisite I have to first setup the project environment so that I would be able to write the required code for uploading file into server and process the file data for our application’s need. Create below build.gradle script to add the required project dependencies. I have also specified the JDK version I will be using for this application.

buildscript {
	ext {
		springBootVersion = '2.2.5.RELEASE' to 2.4.3
	}
    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-file-upload</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.5.RELEASE to 2.4.3</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
                <maven.compiler.source>12</maven.compiler.source>
		<maven.compiler.target>12</maven.compiler.target>
	</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>
			</plugin>
		</plugins>
	</build>
</project>

application.properties

I am creating below application.properties file under classpath directory src/main/resources to override default file upload size 2MB. So maximum file size that I can upload is 10MB. Now you can upload a file with maximum size up to 10MB.

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

Spring REST Controller

Create below class that will be used in file upload example using Spring REST Controller to receive the selected file from client.

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

I use the data type as MultipartFile to upload the file (multipart/form-data).

In the controller method I check whether file has been uploaded or not and if uploaded then I extract the file information and log using Java’s built-in logger API.

Finally I send the file name as the response to the client. In real application, ideally you would process the file data in Service layer code after receiving the file in Spring REST Controller but here I have just shown the idea how to upload a file using Spring REST service.

package com.roytuts.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 FileUploadRestController {

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

	@PostMapping("/upload")
	public ResponseEntity<String> uploadData(@RequestParam("file") MultipartFile file) throws Exception {

		if (file == null) {
			throw new RuntimeException("You must select the a file for uploading");
		}

		InputStream inputStream = file.getInputStream();
		String originalName = file.getOriginalFilename();
		String name = file.getName();
		String contentType = file.getContentType();
		long size = file.getSize();

		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>(originalName, HttpStatus.OK);
	}

}

Spring Boot Main Class

Create below 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.

You need to scan the base packages so that each annotated class (@Controller, @RESTController, @Repository, @Service, @Component etc.) will be picked up from that package or child packages.

package com.roytuts.main;

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

@SpringBootApplication(scanBasePackages = "com.roytuts")
public class Application {

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

}

Testing the Application

Now it’s time to test our file upload example application. You can test this application using REST client, i.e., using Postman and you don’t need any fancy UI for that.

Now open Postman REST client and upload any file and check the output in the console logger.

You need to do the following steps:

  1. Choose http method as POST
  2. Choose form-data in the body option
  3. Put the value for key as file
  4. Choose File instead of Text
  5. Browse and select file
  6. Click on Send.
file upload example using spring rest controller

Console Output

The console output will display about the file information:

936  INFO 18504 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
937  INFO 18504 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
939  INFO 18504 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
113  INFO 18504 --- [nio-8080-exec-2] c.r.controller.FileUploadRestController  : inputStream: java.io.FileInputStream@1bf3ba5e
113  INFO 18504 --- [nio-8080-exec-2] c.r.controller.FileUploadRestController  : originalName: employee.sql
113  INFO 18504 --- [nio-8080-exec-2] c.r.controller.FileUploadRestController  : name: file
113  INFO 18504 --- [nio-8080-exec-2] c.r.controller.FileUploadRestController  : contentType: application/x-sql
114  INFO 18504 --- [nio-8080-exec-2] c.r.controller.FileUploadRestController  : size: 2750

That’s all. Hope you got idea on file upload example using Spring REST Controller.

Source Code

Download

Leave a Reply

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