Upload file using React and Spring Boot

You may also like to read:

Introduction

In this tutorial we will see how to upload file using React and Spring Boot technologies. React or React JS will be used as a client side or front end technology and Spring Boot will be used as a server side technology for uploading file. We will upload file to server using Spring REST API. As a server side technology we will use Spring Boot 2.1.6 and in client side we will use React JS.

You may also like to read Download file using React and Spring Boot.

Prerequisites

Eclipse Neon, Java 1.8, Spring Boot 2.1.6, Gradle 5.4.1

Upload file to server using React

Example with Source Code

Creating Project

Create gradle based project in Eclipse, the project structure may look similar to the below image:

upload file to server using react and spring boot

Updating Build Script

Update the default generated content in build script. You need to include the required dependency for Spring Boot.

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

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

repositories {
    mavenLocal()
    mavenCentral()
}

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

Creating REST Controller

The Spring REST Controller class is responsible for handling request/response for the end users or clients.

Here in the below Spring REST controller class, we upload file the data as a MultipartFile. We give a name to this multipart parameter name as file.

We also validate in the REST method whether a file was selected or not for uploading. So if value for parameter file is null then we throw an exception.

In the below Spring REST controller class we don’t perform any business with the file data but we just log the file information into the console to verify that our file has been uploaded successfully.

Another important thing is we need to allow the host and port from where we are going to upload the file. So in this example we are allowing http://localhost:3000. If you want to allow from anywhere then you can put *.

package com.jeejava.spring.fileupload.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.CrossOrigin;
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
@CrossOrigin(value = "http://localhost:3000")
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 Main Class

Create below main class to deploy the application into embedded Tomcat server.

This is the beauty of Spring Boot application that you don’t need to deploy on external server, you don’t need to create deployment descriptor.

We mention base package to scan so that all the Spring annotated classes will be auto scanned and detected by Spring container.

package com.jeejava.spring.fileupload;

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

@SpringBootApplication(scanBasePackages = "com.jeejava.spring.fileupload")
public class SpringFileUploadApp {

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

}

Testing the Application

Run the main class to deploy the application into Tomcat server.

Also run the Upload file to server using React to open in browser.

The React JS application will start at http://localhost:3000 and open in a default browser.

Home Page

The home page of the application looks to the similar image as shown below:

upload file using react and spring boot

File – Selection

When you select a file using browse button:

upload file using react and spring boot

File – Upload Success

When file successfully uploaded to the server:

upload file using react and spring boot

Server – Console Output

INFO 13876 --- [nio-8080-exec-2] c.j.s.f.r.c.FileUploadRestController     : inputStream: java.io.FileInputStream@7095f10c
INFO 13876 --- [nio-8080-exec-2] c.j.s.f.r.c.FileUploadRestController     : originalName: RepositionBookingList.pdf
INFO 13876 --- [nio-8080-exec-2] c.j.s.f.r.c.FileUploadRestController     : name: file
INFO 13876 --- [nio-8080-exec-2] c.j.s.f.r.c.FileUploadRestController     : contentType: application/pdf
INFO 13876 --- [nio-8080-exec-2] c.j.s.f.r.c.FileUploadRestController     : size: 1614

Source Code

You can download source code.

Thanks for reading.

Upload file using React and Spring Boot

Leave a Reply

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

Scroll to top