2

In my ReactJS project, I'm trying to store images in Firebase Realtime Database as a Base64 url and then convert back to an image on render.

(Note: I know that firestore has this built in, however it's too late to rewrite the code to implement the rest of the project on the platform.)

I take the file in via an input:

<input onChange={this.handleImageUpload} className="form-control" type="file" name="profilePicture" id="profilePicture" placeholder="Upload a profle picture"/>

Which runs the handleImageUpload() function:

  handleImageUpload = e => {
    e.preventDefault();
    const imageAsUrl = this.encodeImageFileAsUrl(e.target.files[0]);

    this.setState({
      profilePicture: imageAsUrl
    });

  }

Which calls the encodeImageAsUrl() function with the current file as input:

  encodeImageFileAsUrl = image => {
    const file = image;
    const reader = new FileReader();
    const imageAsUrl = reader.readAsDataURL(file);
    console.log("Image as url = " + imageAsUrl)
    return imageAsUrl;

  } 

The variable 'imageAsUrl' prints as 'undefined' and also note that any image I try is 1.2MB or less.

whelanevan6
  • 143
  • 1
  • 1
  • 4

1 Answers1

1

You need to have a event hook onload where you will get the data

encodeImageFileAsUrl = image => {
    return new Promise(resolve=>{
    const file = image;    

    const reader = new FileReader();
    //Like this
    reader.onload = (e) => {
        //Adding log to check result
        console.log(e.target.result);
        resolve(e.target.result);
    }
    const imageAsUrl = reader.readAsDataURL(file);
  });
} 

handleImageUpload = async(e) => {
    e.preventDefault();
    const imageAsUrl = await this.encodeImageFileAsUrl(e.target.files[0]);

    this.setState({
      profilePicture: imageAsUrl
    });

  }
Deepak Kumar T P
  • 1,076
  • 10
  • 20