Last active
July 27, 2021 06:32
-
-
Save mmyoji/f7d8fc52d3d966a2fa88e32cc7caaaa2 to your computer and use it in GitHub Desktop.
Browser JS: File <-> Base64 String
This file contains hidden or 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
| function fileToBase64(file: File): Promise<string | ArrayBuffer | null> { | |
| return new Promise((resolve, reject) => { | |
| const r = new FileReader() | |
| r.onload = () => resolve(r.result) | |
| r.onerror = (err) => reject(err) | |
| r.readAsDataURL(file) | |
| }) | |
| } | |
| async function base64ToFile(str: string, fileName: string = "newfile.txt", type: string = "text/plain"): Promise<File> { | |
| const res = await fetch(str) | |
| const blob = await res.blob() | |
| return new File([blob], fileName, { type }) | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment