0

I am trying to upload image in component A and send base 64 data of uploaded image to component B. I am facing issue in component A

HTML:

 <input type="file" id="hotspot" (change)="uploadHotSpot($event)">

TS File:

 uploadHotSpot($event){
    var file:File = $event.target.files[0]; 
    var reader:FileReader = new FileReader();

    if (file) {
      reader.readAsDataURL(file); //reads the data as a URL
      this.pin = reader.result;
      console.log(this.pin);
    }
}

Issue: When I upload the image and keep developer tool on, I am able to get the base 64 data on console log but when the debugger tool is closed and I am trying to upload the image I am getting console.log as blank..... Any idea?

5
  • Quick question : if you only share the image between two components, why don't you just send the image instead of the base64 ? Commented Jul 26, 2018 at 7:10
  • I am not sure about your question. What I am trying to do is user is uploading image on component A which will be visible in component B Commented Jul 26, 2018 at 7:13
  • Then why are you converting it to base64 ? You don't need to. Commented Jul 26, 2018 at 7:13
  • what is the approach then can u guide? Commented Jul 26, 2018 at 7:16
  • Well for starters, maybe you should provide a minimal reproducible example, because right now, you don't even have two components. Commented Jul 26, 2018 at 7:17

1 Answer 1

2

Because that's now how it works. You should create an onload callback to get the result. Like so :

uploadHotSpot($event) {
    var file:File = $event.target.files[0]; 
    var reader:FileReader = new FileReader();

    reader.onload = () => {
      this.pin = reader.result;
      console.log(this.pin);
    };

    if (file) {
      reader.readAsDataURL(file); //reads the data as a URL
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.