In this tutorial, you will learn how to display the preview of multiple images before uploading to the server in a React js application using axios HTTP client.
How to Upload Multiple Image with Preview In React Application
Steps to build Multiple Images upload example with Preview using Axios and Multipart File:
Step 1 – Create React App
Run the following command on your cmd to create a new react app:
npx create-react-app my-react-app
To start he React app:
npm start
Check out your React app on this URL: localhost:3000
Step 2 – Install and Set Up Bootstrap
Run following command to install bootstrap library into your react app:
npm install bootstrap --save
Set up bootstrap.min.css file in src/App.js
file:
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
function App() {
return (
<div>
<h2>React JS Multiple Image Upload With Preview</h2>
</div>
);
}
export default App;
Step 3 – Create Multiple Image Upload with Preview Component
Create multiple image upload with a preview form component named ImageUploadPreviewComponent.js in src directory, and use fileReader() function to display preview of images:
import React, { Component } from 'react';
class ImageUploadPreviewComponent extends Component {
fileObj = [];
fileArray = [];
constructor(props) {
super(props)
this.state = {
file: [null]
}
this.uploadMultipleFiles = this.uploadMultipleFiles.bind(this)
this.uploadFiles = this.uploadFiles.bind(this)
}
uploadMultipleFiles(e) {
this.fileObj.push(e.target.files)
for (let i = 0; i < this.fileObj[0].length; i++) {
this.fileArray.push(URL.createObjectURL(this.fileObj[0][i]))
}
this.setState({ file: this.fileArray })
}
uploadFiles(e) {
e.preventDefault()
console.log(this.state.file)
}
render() {
return (
<form>
<div className="form-group multi-preview">
{(this.fileArray || []).map(url => (
<img src={url} alt="..." />
))}
</div>
<div className="form-group">
<input type="file" className="form-control" onChange={this.uploadMultipleFiles} multiple />
</div>
<button type="button" className="btn btn-danger btn-block" onClick={this.uploadFiles}>Upload</button>
</form >
)
}
}
Step 4 – Import Component in App.js
In this step, you need to add ImageUploadPreviewComponent.js file in src/App.js
file:
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import ImageUploadPreviewComponent from './ImageUploadPreviewComponent'
function App() {
return (
<div className="App">
<ImageUploadPreviewComponent/>
</div>
);
}
export default App;
Conclusion
That’s it, you have learned how to show multiple image preview before uploading to the server in a React js app.