Last active
November 24, 2023 19:57
-
-
Save ValchanOficial/c3e908ea4a0235151c8486363e9af85e to your computer and use it in GitHub Desktop.
[Javascript] file to Base64
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
// with undici | |
const getBase64FromUrl = async (url) => { | |
const response = await fetch(url) | |
const arrayBuffer = await response.arrayBuffer() | |
const base64 = Buffer.from(arrayBuffer)toString('base64') | |
return base64 | |
} | |
// without undici | |
const getBase64FromUrl = async (url) => { | |
const data = await fetch(url); | |
const blob = await data.blob(); | |
return new Promise((resolve) => { | |
const reader = new FileReader(); | |
reader.readAsDataURL(blob); | |
reader.onloadend = () => { | |
const base64 = reader.result; | |
resolve(base64); | |
} | |
}); | |
} | |
// from uploaded file | |
const fileToBase64 = (file) => new Promise((resolve, reject) => { | |
const reader = new FileReader(); | |
reader.readAsDataURL(file); | |
reader.onload = () => resolve(reader.result); | |
reader.onerror = reject; | |
}); | |
getBase64FromUrl('https://i.natgeofe.com/n/4f5aaece-3300-41a4-b2a8-ed2708a0a27c/domestic-dog_thumb_square.jpg').then(console.log) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment