Loading, please wait...

A to Z Full Forms and Acronyms

How to upload image in React?

Jul 04, 2020 React, ReactJS, 5697 Views
In this article, we'll learn about the method used for uploading the image file in the React

For any developer who imagines building an application, transferring pictures is a significant part they need to consider. It is a fundamental necessity while making a total application. Record transferring implies a client from a customer machine needs to transfer documents to the server. For instance, clients can transfer pictures, recordings, and so forth on Facebook, Instagram. Likewise, with any programming issue, there are numerous approaches to accomplish this result.

Let start with the project.

First, we have to create a Project using create-react-app or if you have a then you can use that. After that create the Template in which we create an element “File Input” which allows for choosing the file and uploading it.

Using code editor open the App.js of the project and add the following code:

render() 
{
   let $imagePreview = (<div className="previewText image-container">Please select an Image file for Display</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>
    );
}

In the above code, we used two methods i.e. ‘fileChangedHandler’ and ‘second submit’. The ‘fileChangedHandler method is used for giving the option to the user to select the image file. Whereas another method is used for uploading the file into the Server. So the code is:

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

In this above code, we create the object i.e. “FormData”, that stored the file in it and upload it to the server. All the code adds to the App.js file and at last runs it using the command, npm start.

So this is just a demo example for upload the file by using the template or you can change according to your objective.

A to Z Full Forms and Acronyms