Created
June 20, 2020 22:16
-
-
Save VitorLuizC/ae2a57e83004ecd2d1555637404ea75f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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