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

71 Comments

  1. as said:

    This is great, nice work

    January 9, 2020
    Reply
  2. order cialis said:

    A lot of thanks for all your valuable efforts on this site. Kate loves engaging in investigation and it’s really easy to understand why. I know all concerning the dynamic medium you give important secrets on this web blog and as well as foster participation from others on that content plus our daughter is always discovering a lot. Have fun with the remaining portion of the new year. You are conducting a great job. https://lvagroupinc.com/

    January 7, 2021
    Reply
  3. finasteride tablets said:

    I happen to be writing to make you understand what a useful experience our princess went through visiting yuor web blog. She realized too many things, with the inclusion of what it is like to possess an incredible teaching style to make the rest without problems understand various very confusing topics. You undoubtedly surpassed visitors’ expected results. Thanks for supplying those warm and friendly, trustworthy, revealing not to mention unique tips on your topic to Tanya. https://harrington-service.com/

    January 8, 2021
    Reply
  4. doujinth said:

    ดู คลิป xxx ออนไลน์ หนังโป๊ น หั ง โป๊ ดู ห รัง โป ดู นั ง เอก หนังเอ็กซ์ การ์ตูนxxxซับไทย ค ริบ หนัง โป ดู หนัง ฌ ป้ ดหี doujinth ดู คลิปโป้ หนัง โป๊ หนัง เอ็ ก ดู porn ดู นั ง เอก คลิปโปี เกย์อมควย บ๊อบสั้น นั ง โป็ ฟรี การ์ตูนxxxซับไทย ดูหนังตลกออนไลน์ ดู ห รัง โป ห นั โบ หังx หนังโป๊ ไทย doujinth คลิป โป๊ ออ sหนังออนไลน์ ดหี พริตตี้ นั ง โป็ ฟรี ดู หนัง ฌ ห รัง av ค ริบ หนัง โป ดู หั ง เอ็ ก ดุหนังโป้ฟรี การ์ตูนxxxซับไทย ดู ห รัง โป ดู หนัง โปั ง ดู หนัง ฌ ป้ หนังโป๊ หนัง โป้ ออนไลน์ xxx โลกโป๊ เว็บ x ฟรี เว็บ x ฟรี หนังโปีออนไลน์ หนังโป๊ ไทย doujinth หนัง x ดูฟรี หนัง porn ออนไลน์ คลิป โป้ ควย คลิป โป๊ ออ ดู คลิปโป้ หมาตลก นั ง โป็ ฟรี หังx หนัวโป นั ง โป็ ฟรี เว็บ x ฟรี ดูหนังเอ๊กซ์ หนัง x ฟี ร doujinth ดู หนัง คลิป โป๊ ออนไลน์ หนังโป้ออไล หนังโป๊เ คลิปโปี ดู ก นั ง xx หนังเอ็กซ์ clip pron ดู หนัง โป๋ ออ น ไล ฟรี การ์ตูนโป๊เกย์ ดหี

    January 8, 2021
    Reply
  5. order remeron said:

    My spouse and i felt now fortunate that Emmanuel could conclude his investigation out of the ideas he gained in your web page. It’s not at all simplistic to just choose to be giving freely information and facts that many other folks have been selling. And we all figure out we have the website owner to be grateful to for that. The explanations you have made, the simple site menu, the friendships you can give support to engender – it’s got everything fabulous, and it’s really facilitating our son and the family feel that the idea is enjoyable, and that is incredibly important. Thank you for all the pieces! https://remeronmirtazapine.com

    January 8, 2021
    Reply
  6. paroxetine cost said:

    I happen to be writing to make you understand what a wonderful experience our princess went through visiting yuor web blog. She realized too many things, with the inclusion of what it is like to possess an incredible teaching style to make the rest without problems understand various very confusing topics. You undoubtedly surpassed visitors’ expected results. Thanks for supplying those warm and helpful, trustworthy, revealing not to mention unique tips on your topic to Tanya. https://paxilparoxetines.com/

    January 9, 2021
    Reply
  7. Mikayla said:

    Hi i am kavin, its my first time to commenting anyplace, when i read this piece of writing i
    thought i could also create comment due to this good article.

    Also visit my web-site – หนังใหม่ชนโรง

    January 18, 2021
    Reply
  8. WWW.XMC.PL said:

    I was browsing on the net for some info since yesterday night and I at last found what i was looking for! This is a fantastic website by the way, but it seems a slight difficult to read on my att phone.

    January 28, 2021
    Reply
  9. Klara said:

    You need to be a part of a contest for one of the highest quality websites on the internet.

    I’m going to recommend this web site!

    Take a look at my blog post: cheap flights

    January 29, 2021
    Reply
  10. Lavonda said:

    Great article, just what I wanted to find.

    Also visit my web site; cheap flights

    January 29, 2021
    Reply
  11. Lenard said:

    Ahaa, its good conversation about this paragraph here at this blog, I have read all that,
    so at this time me also commenting here.

    Also visit my page … cheap flights

    January 30, 2021
    Reply
  12. Wanda said:

    Outstanding story there. What occurred after?
    Thanks!

    Also visit my blog cheap flights

    January 31, 2021
    Reply
  13. Karin said:

    Thanks for your marvelous posting! I really enjoyed reading it, you are a great author.I will be sure
    to bookmark your blog and will often come back later in life.

    I want to encourage you to continue your great job, have a nice evening!

    Stop by my blog – cheap flights

    February 1, 2021
    Reply
  14. XMC EDU said:

    Presently its good timing to make a few plans for the long run and it is time to be happy. Ive learn this put up and if I may I desire to counsel you some interesting issues or suggestions. Perhaps you could post subsequent material regarding this article. I want to learn more things related to it!

    February 1, 2021
    Reply
  15. Ying Hird said:

    I know that there are countless plug-ins designed to make the comments do-follow, but I’m looking for something that will make the links in the blog-posts themselves do-follow. Please include a link or detailed instructions on how to do this. Thanks!. Do you have any examples of themes that you know for a fact have do-follow links in the posts? I’m having a hard time finding good information about this by searching..

    February 2, 2021
    Reply
  16. WWW.XMC.PL Portal said:

    Would you be curious about exchanging hyperlinks?

    February 2, 2021
    Reply
  17. Mamie said:

    For newest information you have to go to
    see world wide web and on the web I found this website as a best site for hottest updates.

    Feel free to visit my page – cheap flights, tinyurl.com,

    February 2, 2021
    Reply
  18. Michael said:

    What’s Taking place i am new to this, I stumbled
    upon this I have discovered It absolutely
    useful and it has aided me out loads. I am hoping to contribute &
    help other users like its helped me. Good job.

    My blog: cheap flights

    February 2, 2021
    Reply
  19. Leora said:

    I do consider all the ideas you’ve offered to your post.

    They’re very convincing and will definitely work. Nonetheless, the posts are very quick for starters.
    May you please prolong them a little from next time?
    Thanks for the post.

    Also visit my web site; cheap flights (tinyurl.com)

    February 3, 2021
    Reply
  20. KuikCuddy said:

    questions about viagra i need viagra shopping generic viagra

    February 7, 2021
    Reply
  21. Aqcfgedecuddy said:

    viagra cheap generic cialis generuc cialis cialis shop

    February 8, 2021
    Reply
  22. https://www.yamatocosmos.com said:

    best i have ever seen !

    February 8, 2021
    Reply
  23. Lbsxguany said:

    viagra online canadian pharmacy viagra generic canada pharmacy online no script

    February 8, 2021
    Reply
  24. Kbcxbype said:

    canadian pharmacies that ship to us blood pressure pharmacy on line

    February 9, 2021
    Reply
  25. Mac said:

    I think what you published made a bunch of sense.
    However, what about this? what if you wrote a catchier title?

    I ain’t suggesting your content isn’t solid,
    however what if you added a headline that makes people want more?
    I mean React image upload or file upload with preview is a little plain. You
    ought to glance at Yahoo’s home page and see how they create article titles to get viewers to open the links.

    You might add a video or a related pic or two to grab readers
    interested about everything’ve written. In my opinion, it could make your posts a
    little bit more interesting.

    my web page – cheap flights (http://tinyurl.com/)

    February 12, 2021
    Reply
  26. Cody said:

    Hello, i feel i saw you visited my site thus i got here to return the favor?.I
    am seeking to find issues to improve my internet site!I assume its sufficient to make use of a few
    of your ideas!!

    Have a look at my site :: CarlotaSDuel

    February 12, 2021
    Reply
  27. NbnhGeste said:

    how to order viagra online safely sildenafil cream super viagra online

    February 14, 2021
    Reply
  28. Labxguany said:

    cialis 5 mg c/28 cialis nice wie schnell wirkt cialis

    February 16, 2021
    Reply
  29. Danae said:

    Ambedkar College Yamuna Vihar 20th Century Brazilian Writers

    My website :: pdf base

    February 16, 2021
    Reply
  30. Patsy said:

    Materials Science And Engineering A First Course Pdf
    Backyard Science Grenade

    Feel free to visit my website – library

    February 17, 2021
    Reply
  31. Anika Mazikowski said:

    My computer crashes at the start of a streaming video or of a full windowed video game?

    February 17, 2021
    Reply
  32. Gigi Mckibbin said:

    How do I start a blog with payment options for readers?

    February 17, 2021
    Reply
  33. Arron said:

    My Family And Other Animals Gerald Educational Experience In Cv

    Also visit my homepage; wordpress.com

    February 17, 2021
    Reply

Leave a Reply

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