Base64 to String in javascript

582 views Asked by At

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 :(

1

There are 1 answers

2
Samathingamajig On

"what I need is to pass the result that the console.log gives me to show it on the screen as a string"

then just do that

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>