-1

I've been trying to find a way to Base64 encode binary data with JavaScript for the past few hours and it turns out that btoa() only works with strings so I came up with the following code, where blob is the file I need to encode:

function base64Encode(blob) {
    var reader = new FileReader();
    reader.readAsDataURL(blob)
    reader.onloadend = function() {
        console.log(reader.result);
    };
};

Problem is, base64Encode(blob) always returns undefined, does anybody know a fix?

  • try just to put your function in onload, not onloadend. Also, is there any chance your blob is malformed? – Markido Aug 16 '21 at 10:06
  • Your function `base64Encode` does not return anything, so implicit `undefined` is returned. – Sven Eberth Aug 16 '21 at 10:07
  • 1. Any function that has no `return` statement “returns undefined”. 2. readAsDataUrl is async. [read more](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call/14220323#14220323) – James Aug 16 '21 at 10:07

1 Answers1

1

You are not returning anything from your function, you could use promises and async/await. As an example see the below code, it might help you.

const convertBlobToBase64 = async (blob) => {
  return await blobToBase64(blob);
}

const blobToBase64 = blob => new Promise((resolve, reject) => {
  const reader = new FileReader();
  reader.readAsDataURL(blob);
  reader.onload = () => resolve(reader.result);
  reader.onerror = error => reject(error);
});

caller:

console.log(await convertBlobToBase64(someFileData));
this.srivastava
  • 1,045
  • 12
  • 22