2

I am trying to convert my uploaded image to a base64 before sending it to the backend for processing, and I am using readAsDataUrl for doing the same, but the result comes as null always,

convertToBase64 () --


    const convertFileToBase64 = file => new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file.rawFile);
    
      reader.onload = () => resolve(reader.result);
      reader.onerror = reject;
    });

Blob :

{
    "rawFile": {
        "path": "Logo.png"
    },
    "src": "blob:http://localhost:3000/5ff2faa0-6f37-4c2e-906a-4c953d146efa",
    "title": "Logo.png"
}

I am passing this blob as a file parameter to my convertToBase64 method, but reader.result is null always While debugging I can see the promise being still pending and not resolved, could this be the reason it being null? How do I fix this?

sample-user
  • 31
  • 1
  • 8

2 Answers2

0

Try this

const convertFileToBase64 = file => new Promise((resolve, reject) => {
  const reader = new FileReader();
  reader.readAsDataURL(file.rawFile.path); //path of the file

  reader.onload = () => resolve(reader.result);
  reader.onerror = reject;
});
0

If you're passing in a blob as file then you can probably change reader.readDataAsURL(file.rawFile) to just reader.readDataAsURL(file)

This worked for me:

index.html

...
<body>
  <input type="file" id='file'/>
  <script src='./app.js'></script>
</body>

app.js

const fileReader = document.getElementById('file')

const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const fr = new FileReader()

    console.log(file instanceof Blob) // Should be true

    fr.readAsDataURL(file)
    fr.onerror = reject
    fr.onload = function () {
      resolve(fr.result)
    }
  })
}

fileReader.addEventListener('change', (e) => {
  getBase64(e.target.files[0]).then((res) => console.log(res) )
})

Dharman
  • 30,962
  • 25
  • 85
  • 135
srosser2
  • 91
  • 5