React Spring Boot Multiple File Upload Example (2024)
In this tutorial, we'll show you how to create React + Spring Boot upload multiple files example using http
post
and multipart
.
POST
- Upload multiple filesFile Size
- Check for file size exceeded.Error Handling
- Handle the error while uploading files.
React Upload Multiple File Implementation
Create React Multiple Files Upload Project
Create the new React App for multiple file upload using below command:
npx create-react-app reactjs-multiple-file-upload
Project Structure
According to the project's use case or requirements, we can create files and folders.
Dependencies
Below dependencies get added in package.json
, once we create the project and to install
these dependencies use command npm install
file.
{
"name": "reactjs-multiple-file-upload",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"bootstrap": "^4.6.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Checkout our related posts :
Upload File Component
Create Upload File UploadFile.js
, which will do below functions:
POST
- Upload multiple files usinghttp post
.File Size
- Check for file size exceeded.Uploading Progress Message
- Added message for showing progress, user can replace with any image as per use case.Error Handling
- Handle the error while uploading files.
import React, { useState } from 'react';
const UploadFile = () => {
const [files, setFiles] = useState('');
//state for checking file size
const [fileSize, setFileSize] = useState(true);
// for file upload progress message
const [fileUploadProgress, setFileUploadProgress] = useState(false);
//for displaying response message
const [fileUploadResponse, setFileUploadResponse] = useState(null);
//base end point url
const FILE_UPLOAD_BASE_ENDPOINT = "http://localhost:8282";
const uploadFileHandler = (event) => {
setFiles(event.target.files);
};
const fileSubmitHandler = (event) => {
event.preventDefault();
setFileSize(true);
setFileUploadProgress(true);
setFileUploadResponse(null);
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
if (files[i].size > 1024){
setFileSize(false);
setFileUploadProgress(false);
setFileUploadResponse(null);
return;
}
formData.append(`files`, files[i])
}
const requestOptions = {
method: 'POST',
body: formData
};
fetch(FILE_UPLOAD_BASE_ENDPOINT+'/upload', requestOptions)
.then(async response => {
const isJson = response.headers.get('content-type')?.includes('application/json');
const data = isJson && await response.json();
// check for error response
if (!response.ok) {
// get error message
const error = (data && data.message) || response.status;
setFileUploadResponse(data.message);
return Promise.reject(error);
}
console.log(data.message);
setFileUploadResponse(data.message);
})
.catch(error => {
console.error('Error while uploading file!', error);
});
setFileUploadProgress(false);
};
return(
<form onSubmit={fileSubmitHandler}>
<input type="file" multiple onChange={uploadFileHandler}/>
<button type='submit'>Upload</button>
{!fileSize && <p style={{color:'red'}}>File size exceeded!!</p>}
{fileUploadProgress && <p style={{color:'red'}}>Uploading File(s)</p>}
{fileUploadResponse!=null && <p style={{color:'green'}}>{fileUploadResponse}</p>}
</form>
);
}
export default UploadFile;
Refer React Multiple File Upload Example for full implementation with Source Code.
Spring Boot Upload Multiple File Implementation
Create Spring Boot Project from Spring Initializer site https://start.spring.io/
Project Structure
Maven Dependency
All we need is spring-boot-starter-web
dependency in pom.xml, add org.projectlombok
for auto generating getters/setters/constructor.
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.techgeeknext</groupId>
<artifactId>spring-boot-upload-multiple-files-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-upload-multiple-files-example</name>
<description>Spring Boot upload multiple files example</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
RestController to upload multiple files
Create RestController class and define below rest endpoint:
POST
method to Upload multiple files usingMultipartFile[] files
as a parameter.GET
method to list all files from the file storage folder.
package com.techgeeknext.controller;
import com.techgeeknext.util.FileUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Controller
//@CrossOrigin(origins = "http://localhost:8082") open for specific port
@CrossOrigin() // open for all ports
public class MultipleFilesUploadController {
/**
* Method to upload multiple files
* @param files
* @return FileResponse
*/
@PostMapping("/upload")
public ResponseEntity<FileUploadResponse> uploadFiles(@RequestParam("files") MultipartFile[] files) {
try {
createDirIfNotExist();
List<String> fileNames = new ArrayList<>();
// read and write the file to the local folder
Arrays.asList(files).stream().forEach(file -> {
byte[] bytes = new byte[0];
try {
bytes = file.getBytes();
Files.write(Paths.get(FileUtil.folderPath + file.getOriginalFilename()), bytes);
fileNames.add(file.getOriginalFilename());
} catch (IOException e) {
}
});
return ResponseEntity.status(HttpStatus.OK)
.body(new FileUploadResponse("Files uploaded successfully: " + fileNames));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED)
.body(new FileUploadResponse("Exception to upload files!"));
}
}
/**
* Create directory to save files, if not exist
*/
private void createDirIfNotExist() {
//create directory to save the files
File directory = new File(FileUtil.folderPath);
if (! directory.exists()){
directory.mkdir();
}
}
/**
* Method to get the list of files from the file storage folder.
* @return file
*/
@GetMapping("/files")
public ResponseEntity<String[]> getListFiles() {
return ResponseEntity.status(HttpStatus.OK)
.body( new File(FileUtil.folderPath).list());
}
}
Refer Spring Boot Api's for Upload Multiple File Example for full implementation with Source Code.
Test Reactjs Spring Boot Multiple File Upload Example
- Prerequisite : Start the Spring Boot Rest Api's application required for our react example.
- Use below command to install all the dependencies required for the project.
npm install
- Run the application by using below command:
npm start
- By default application will open in browser at http://localhost:3000/ url.
-
Upload Files
Choose File(s) and click on Upload button to upload the multiple/single files using rest endpoint. Check for File Exceeded
Use big size file to validate for file exceeded validation.
Download Source Code
The full source code for this article can be found below.
- Download it here - Spring Boot Upload Multiple Files Example
- Download it here - React Upload Multiple Files Example