Skip to content

Instantly share code, notes, and snippets.

@hungtcs
Created December 26, 2023 01:22
Show Gist options
  • Save hungtcs/0efd7bfc3ff59ec57972233280d6dfcc to your computer and use it in GitHub Desktop.
Save hungtcs/0efd7bfc3ff59ec57972233280d6dfcc to your computer and use it in GitHub Desktop.
Convert base64 string to File
function base64ToFile(base64: string, filename: string) {
const [header, code] = base64.split(',')
const cotnentType = header.replace(/(data:)|(;base64)/g, '');
const byteStr = atob(code);
const bytes = new Array(byteStr.length);
for (var i = 0; i < byteStr.length; i++) {
bytes[i] = byteStr.charCodeAt(i);
}
const byteArray = new Uint8Array(bytes);
const blob = new Blob([byteArray], { type: cotnentType });
return new File([blob], filename, { type: blob.type });
}
function fileToBase64(file: File) {
return new Promise<string>((resolve, reject) => {
var reader = new FileReader();
reader.onload = function (e) {
resolve(e.target.result as string);
};
reader.onerror = reject;
reader.onabort = reject;
reader.readAsDataURL(file);
});
}
async function main() {
const base64 = `data:image/gif;base64,R0lGODlhCgAKAJEAAP////8AAAAA/wAAACH5BAAAAAAALAAAAAAKAAoAAAIWjC2Zhyoc3DOgAnXslfqo3mCMBJFMAQA7`
const file = base64ToFile(base64, '00.png')
console.log(file);
console.log(await fileToBase64(file) === base64);
}
main().catch((err) => console.error(err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment