11

Upload Single and Multiple Images with Preview in React with Example

 1 year ago
source link: https://www.laravelcode.com/post/upload-single-and-multiple-images-with-preview-in-react-with-example
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Upload Single and Multiple Images with Preview in React with Example

  40122 views

  2 years ago

React

Today in this React image upload preview tutorial, we are going to learn how to show image preview before uploading to the server in a React app. We will create a basic react app in which we will use an HTML file input field along with some events to show an image preview.

Let’s understand the URL.createObjectURL() static method, we are going to use this method to get the image preview URL. This method generates a DOMString including a URL describing the object yielded in the parameter. The URL life is tied to the document in the window on which it was created. The new object URL outlines the designated File object or Blob object.

myObjectURL = URL.createObjectURL(object);

object: It’s a Blob, File or MediaSource object, It creates an object URL.

Return value: A DOMString including an object URL that represents the contents of the particular source object.

React 16+ Single and Multiple Images Upload Preview

Let’s install the React app for image upload preview demo.

Install React with Bootstrap

In the very first step, Install the React app with Bootstrap 4. Execute the given below command.

npx create-react-app react-image-preview

Navigate to React image preview app directory.

cd react-image-preview

Next, install the Bootstrap 4 framework.

npm install bootstrap --save

Next, Import bootstrap.min.css in src/App.js file from node_modules folder:

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';

function App() {
  return (
    <div className="App">
      <h3>Image Upload Preview in React</h3>
    </div>
  );
}

export default App;

Next, run the React app in the web browser.

npm start

Create Single Image Upload Preview

Create src > components directory and create two component files inside of it. Name these files single-image-upload.component.js and multiple-image-upload.component.js.

Add below code in single-image-upload.component.js file.

import React, { Component } from 'react';

export default class SingleImageUploadComponent extends Component {

    constructor(props) {
        super(props)
        this.state = {
            file: null
        }
        this.uploadSingleFile = this.uploadSingleFile.bind(this)
        this.upload = this.upload.bind(this)
    }

    uploadSingleFile(e) {
        this.setState({
            file: URL.createObjectURL(e.target.files[0])
        })
    }

    upload(e) {
        e.preventDefault()
        console.log(this.state.file)
    }

    render() {
        let imgPreview;
        if (this.state.file) {
            imgPreview = <img src={this.state.file} alt='' />;
        }
        return (
            <form>
                <div className="form-group preview">
                    {imgPreview}
                </div>

                <div className="form-group">
                    <input type="file" className="form-control" onChange={this.uploadSingleFile} />
                </div>
                <button type="button" className="btn btn-primary btn-block" onClick={this.upload}>Upload</button>
            </form >
        )
    }
}

We defined the HTML form and added the React events with HTML attributes. Initiate the input file field state in the constructor method, then set the state of the input filed in uploadSingleFile() method.

Next, we defined the if statement inside the render() method, because initially, image tag doesn’t have any preview url. We are setting up the image preview url when the user uploads the image.

We took a simple approach rather than using FileReader() web API in image upload preview. We used the URL.createObjectURL() static method which produces a DOMString including a URL representing the object provided in the parameter.

Multiple Images Upload Preview in React

Now, let’s build multiple images upload preview component, include the given below code within the multiple-image-upload.component.js file.

import React, { Component } from 'react';

export default class MultipleImageUploadComponent 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 >
        )
    }
}

Define fileObj array variable, we will insert image preview urls in this array using URL.createObjectURL() method for showing multiple images preview before uploading to the server.

Next, we defined fileArray array in this array we will push images to preview url we are using JavaScript’s map() method to iterate over the fileArray. Then we are setting up the tag and passing the image url return by map method.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK