1

In Angular, I have the following code which records audio, get the blob, and converts it to base64, using FileReader. But I'm not able to return this base64 data from onloadend method of file reader

  getRecordedAudio() {
    if (this.recordedAudio) {
      let fileReader = new FileReader();    
      fileReader.onloadend = function() {
        let base64data = fileReader.result;
        console.log('base64data-', base64data);
        // how to return here?
      };
      fileReader.readAsDataURL(this.recordedAudio);
    }
  }

How can I do this using either callback or .then? Or any other way?

1 Answer 1

1

The short answer is: you cannot return there;

the onloadend function will be called asynchronously, so returning would not send the value anywhere.

You can call a service directly from this onloadend to send this file somewhere(i.e. backend)

...
fileReader.onloadend = function() {
        let base64data = fileReader.result;
        console.log('base64data-', base64data);
        this.yourService.uploadFile(base64data)
      };
...

or save its contents in a component variable

...
fileReader.onloadend = function() {
        let base64data = fileReader.result;
        console.log('base64data-', base64data);
        this.yourVariable = base64data;
      };
...

also you might want to do some reading about the FileReader object, this site explains it well

fileReader.result does not seem to return a base64 string... you might need to do some conversion there.

4
  • you can also return a promise or use an observable, what would you be doing with the contents of the base64data variable? more javascript or sending it somewhere?
    – The Fabio
    Commented Oct 20, 2019 at 13:40
  • I want to send the base64 data to server, and play it using audio element Commented Oct 20, 2019 at 13:58
  • I will suggest you use the service approach from above. i just updated the answer with some resources for you to use,
    – The Fabio
    Commented Oct 20, 2019 at 14:06
  • Thank you. Can you answer this? stackoverflow.com/questions/58473636/… It's related Commented Oct 20, 2019 at 14:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.