0

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?

user5155835
  • 2,890
  • 2
  • 24
  • 64

1 Answers1

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.

The Fabio
  • 2,454
  • 1
  • 17
  • 32
  • 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 Oct 20 '19 at 13:40
  • I want to send the base64 data to server, and play it using audio element – user5155835 Oct 20 '19 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 Oct 20 '19 at 14:06
  • Thank you. Can you answer this? https://stackoverflow.com/questions/58473636/angular-filereader-base64-remove-preceding-data It's related – user5155835 Oct 20 '19 at 14:11