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. Here we will create Spring Boot application as it reduces our most of the efforts in project configurations.

Recommended reading:

Junit Testing of File Upload and Download in Spring REST Controllers

File download example using Spring REST Controller

Prerequisites

Knowledge of Spring REST API
Eclipse
JDK 1.8
Gradle
Spring Boot dependencies

Setting up project

As a prerequisite we have to first setup the project environment so that we 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. We have also specified the JDK version we will be using for our application.

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

apply plugin: 'java'
apply plugin: 'org.springframework.boot'

jar {
    baseName = 'SpringBootFileUpload'
    version = '0.0.1-SNAPSHOT'
    manifest {
        attributes("Main-Class": "com.jeejava.main.Application")
    }
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
	mavenLocal()
    mavenCentral()
}
    
dependencies {
	compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
}

Creating application.properties file

We are creating below application.properties file under classpath directory src/main/resources to override default file upload size 2MB and also we don’t want to start our server run on default port 8080. So we want our server to be started on 9999 port and maximum file size that we can upload is 10MB. Now you can upload a file with maximum size upto 10MB.

server.port=9999

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

Creating 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. We have the below method with http method POST request and request file parameter uploadfile which we will be used for uploading file from client. We use the data type as MultipartFile to upload the file(multipart/form-data). In the controller method we check whether file has been uploaded or not and if uploaded then we extract the file information and log using Java’s built-in logger API. Finally we 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.jeejava.controller;

import java.io.InputStream;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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);
	}
                
}

Creating the 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 9999 instead of default port as we have override it in application.properties file. 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.jeejava.app;

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

@SpringBootApplication(scanBasePackages = "com.jeejava")
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. We 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:

INFO 26416 --- [nio-9999-exec-2] c.j.controller.FileUploadRestController  : inputStream: java.io.FileInputStream@40bf18e9
INFO 26416 --- [nio-9999-exec-2] c.j.controller.FileUploadRestController  : originalName: Test.txt
INFO 26416 --- [nio-9999-exec-2] c.j.controller.FileUploadRestController  : name: file
INFO 26416 --- [nio-9999-exec-2] c.j.controller.FileUploadRestController  : contentType: text/plain
INFO 26416 --- [nio-9999-exec-2] c.j.controller.FileUploadRestController  : size: 2066

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

Recommended reading:

Junit Testing of File Upload and Download in Spring REST Controllers

File download example using Spring REST Controller

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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