Skip to content

Instantly share code, notes, and snippets.

@VitorLuizC
Created June 20, 2020 22:16
Show Gist options
  • Save VitorLuizC/ae2a57e83004ecd2d1555637404ea75f to your computer and use it in GitHub Desktop.
Save VitorLuizC/ae2a57e83004ecd2d1555637404ea75f to your computer and use it in GitHub Desktop.
/**
* Transforms blob to base64 using FileReader API.
* @param blob - A blob instance.
*/
const fromBlobToBase64 = (blob: Blob): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = (): void => {
reject(reader.error ?? new Error('Unknown error on FileReader.'));
};
reader.onload = (event: ProgressEvent<FileReader>): void => {
const data = event.target?.result;
if (typeof data !== 'string') {
reject(new Error('FileReader returned non-string data.'));
return;
}
resolve(btoa(data));
};
reader.readAsBinaryString(blob);
});
};
/**
* Receives a path of asset location, fetch is as blob and transform to base64.
* @param path - Path to asset location.
*/
const getAssetInBase64 = (path: string): Promise<string> => {
return fetch(path)
.then(response => response.blob())
.then(fromBlobToBase64);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment