user5155835
user5155835

Reputation: 4742

Angular filereader onloadend return result

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?

Upvotes: 1

Views: 3781

Answers (1)

The Fabio
The Fabio

Reputation: 6250

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.

Upvotes: 1

Related Questions