React Multiple File Upload Example (2024)
In this tutorial, we'll show you how to create React 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.
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;
Integrate file upload component to App
Add UploadFile.js
component into App.js
.
import './App.css';
import UploadFile from './components/UploadFile';
function App() {
return (
<div className="App">
<h2>TechGeekNext Multiple File Upload Example</h2>
<UploadFile />
</div>
);
}
export default App;
Test 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 on below.Download it here - React Upload Multiple Files Example