React image upload or file upload with preview

Today we are going to learn how to upload the file or image in react. Image upload or file upload is a common requirement of the application.

Before start learning react image or file upload. We need a `React Project`. If you don’t know how to create a new project. Follow this tutorial.

So, Let’s get started react image or file upload

Create template

To upload file we need a html template. In this template we will create `file input` element that allows to us to choose the file and a button to upload file. To create it open the `App.js` file and update the render function with the below code.

render() {

    let $imagePreview = (<div className="previewText image-container">Please select an Image for Preview</div>);
    if (this.state.imagePreviewUrl) {
      $imagePreview = (<div className="image-container" ><img src={this.state.imagePreviewUrl} alt="icon" width="200" /> </div>);
    }

    return (
      <div className="App">
         <input type="file" name="avatar" onChange={this.fileChangedHandler} />
         <button type="button" onClick={this.submit} > Upload </button>
         { $imagePreview }
      </div>
    );
}

You may notic that we have two method in this `HTML` Fist `fileChangedHandler` and second `submit`

Let’s write `fileChangedHandler` function

fileChangedHandler = event => {
    this.setState({
      selectedFile: event.target.files[0]
    })

    let reader = new FileReader();
    
    reader.onloadend = () => {
      this.setState({
        imagePreviewUrl: reader.result
      });
    }

    reader.readAsDataURL(event.target.files[0])

  }

The `fileChangedHandler` method will called when the user choose file. It will get the file object of selected file and store in the `selectedFile` state.

Now we will write another function which is responsible to upload the file into the server.

submit = () => {

    var fd = new FormData();

    fd.append('file', this.state.selectedFile);

    var request = new XMLHttpRequest();

    request.onreadystatechange = function() {
      if (this.readyState === 4 &amp;&amp; this.status === 200) {
        alert('Uploaded!');
      }
    };
    request.open("POST", "https://us-central1-tutorial-e6ea7.cloudfunctions.net/fileUpload", true);
    request.send(fd);


}

In this function first we create a new object of the `FormData` and then append the file. then send the request to the server


Here we have crated a `formData` object. We will store the file object to the `formData` and then upload it to the server.

After the all changes our file will looks like this

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  state =  {
    selectedFile: null,
    imagePreviewUrl: null
  };

  fileChangedHandler = event => {
    this.setState({
      selectedFile: event.target.files[0]
    })

    let reader = new FileReader();
    
    reader.onloadend = () => {
      this.setState({
        imagePreviewUrl: reader.result
      });
    }

    reader.readAsDataURL(event.target.files[0])

  }

  submit = () => {

    var fd = new FormData();

    fd.append('file', this.state.selectedFile);

    var request = new XMLHttpRequest();

    request.onreadystatechange = function() {
      if (this.readyState === 4 &amp;&amp; this.status === 200) {
        alert('Uploaded!');
      }
    };
    request.open("POST", "https://us-central1-tutorial-e6ea7.cloudfunctions.net/fileUpload", true);
    request.send(fd);
  }

  render() {

    let $imagePreview = (<div className="previewText image-container">Please select an Image for Preview</div>);
    if (this.state.imagePreviewUrl) {
      $imagePreview = (<div className="image-container" ><img src={this.state.imagePreviewUrl} alt="icon" width="200" /> </div>);
    }

    return (
      <div className="App">
         <input type="file" name="avatar" onChange={this.fileChangedHandler} />
         <button type="button" onClick={this.submit} > Upload </button>
         { $imagePreview }
      </div>
    );
  }
}

export default App;

Running application:

Run the application using npm run start

Preview

Our application will looks like this:

If you loved this tutorial, Please share and if you have any question please comment

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *