React JS Multiple Image Upload with Preview Example

import React, { Component } from ‘react’;
import { Upload, message, Button, Icon } from ‘antd’;

class MultipleImageUpload extends Component {
constructor(props) {
super(props);
this.state = {
previewVisible: false,
previewImage: ”,
fileList: [],
};
}

handleCancel = () => this.setState({ previewVisible: false });

handlePreview = file => {
this.setState({
previewImage: file.url || file.thumbUrl,
previewVisible: true,
});
};

handleChange = ({ fileList }) => this.setState({ fileList });

render() {
const { previewVisible, previewImage, fileList } = this.state;
const uploadButton = (

Upload

);
return (


{fileList.length >= 3 ? null : uploadButton}


example

);
}
}

export default MultipleImageUpload;

React JS multiple image upload preview example; In this tutorial, you will learn how to display multiple image preview before uploading to the server in a React js app.

Multiple image upload allows the user to select multiple files at once and upload all files to the server. index. html Create a simple HTML page to select multiple files and submit it to upload files on the server. Here, the HTML file contains a form to select and upload files using the POST method.

And this tutorial will create a simple react js app in which will use an HTML file input field along with some events to show multiple image preview.

How to Upload Multiple Image with Preview In React Apps

Let’s use the following steps to display multiple image preview before uploading to the server in a React js app.

  • Step 1 – Create React App
  • Step 2 – Install Bootstrap 4
  • Step 3 – Create Multiple Image Upload with Preview Component
  • Step 4 – Add Component in App.js

Step 1 – Create React App

In this step, open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app my-react-app

To run the React app, execute the following command on your terminal:

npm start

Check out your React app on this URL: localhost:3000

Step 2 – Install Bootstrap 4

In this step, execute the following command to install boostrap 4 library into your react app:

npm install bootstrap --save

Add 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

In this step, visit the src directory of your react js app and create multiple image upload with a preview form component named ImageUploadPreviewComponent.js. And add the following code into it:

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 >
        )
    }
}

Here is the breakdown of above given code:

  • This code imports React and Component from the ‘react’ library. It then defines a class component called ImageUploadPreviewComponent that extends the Component class from React.
  • In the constructor, fileObj and fileArray are initialized as empty arrays and the initial state of the component is set with a file property that contains a single null value. The constructor also binds the uploadMultipleFiles and uploadFiles methods to this so they can be used in the component.
  • The uploadMultipleFiles method is called when a user selects one or more files using the input element with the type attribute set to file. This method pushes the selected file(s) to the fileObj array and creates a URL for each file using URL.createObjectURL(). It then pushes these URLs to the fileArray and sets the component’s state to the new fileArray.
  • The uploadFiles method is called when the user clicks the “Upload” button. It simply logs the current file array to the console.
  • The render method returns a form element with a file input that allows the user to select one or more files. The onChange attribute of this input is set to the uploadMultipleFiles method so it is called whenever the selected files change. A preview of the selected files is also displayed using the fileArray array. Finally, there is a button that, when clicked, calls the uploadFiles method.

Step 4 – Add 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

React JS multiple image upload preview example. In this tutorial, you will learn in detail how to show multiple image preview before uploading to the server in a React js app.

Recommended React JS Posts

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?