I have this code that transforms an image url to base64, it works perfectly but I haven't found a way to convert the result to a string, I need to convert it to a string since I have to POST via an API, any idea I'm doing wrong? :(
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}))
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0')
.then(dataUrl => {
console.log('RESULT:', dataUrl)
})
most likely it's something super simple that I'm failing :(
CodePudding user response:
I guess you want to convert dataUrl
to a string like this:
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result?.toString() || "") // <====
reader.onerror = reject
reader.readAsDataURL(blob)
}))
CodePudding user response:
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}))
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0')
.then(dataUrl => {
document.getElementById("blob-string").innerText = dataUrl;
})
<p id="blob-string"></p>