Skip to content

Instantly share code, notes, and snippets.

@mmyoji
Last active July 27, 2021 06:32
Show Gist options
  • Select an option

  • Save mmyoji/f7d8fc52d3d966a2fa88e32cc7caaaa2 to your computer and use it in GitHub Desktop.

Select an option

Save mmyoji/f7d8fc52d3d966a2fa88e32cc7caaaa2 to your computer and use it in GitHub Desktop.
Browser JS: File <-> Base64 String
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