Search code examples
javascriptangularfilereader

How to get results of File reader


So I have an onchange event in my html which gets an image from the user and need to convert it to a data url in order to send over socket.io and store in the database. How do I get the results of my file reader object. I dont know how to pass in a callback

What I need to do is get a callback function into the file reader onload event so that I can set my picture variable to the data url to then send over the socket. Just need help in getting the results from the file reader to my global variable // HTML

<input type = 'file' (change) = "setpreview($event)" value = 'upload photo'>

// the js code.

setpreview(event) {
  var img = <File>event.target.files[0];
  var reader = new FileReader();
  reader.onload = function() {
    console.log(reader.result);
  }

  reader.readAsDataURL(img);
}

Solution

  • You got it just assign the result to a scoped variable and use it in template

    srcImg = null; //declare this
    
    setpreview(event) {
      const comp = this;
      const img = <File>event.target.files[0];
      const promise = new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = function () {
          resolve(reader.result);
        }
        reader.readAsDataURL(img);
      });
    
      promise.then(img => {
        comp.srcImg = img;
        // if you want to do anything with img you can do it here
      });
    }
    
    <input type = 'file' (change) = "setpreview($event)" value = 'upload photo'>
    <img [src]="srcImg" *ngIf="srcImg" />
    

    Updated Stackblitz: https://stackblitz.com/edit/angular-tkbbdh