2

Am trying to upload files as base64 in javascript but it throws error.

TypeError: FileReader.readAsDataURL: Argument 1 does not implement interface Blob.

here is the code

  <input id="file" type="file"/>
  <button id="button">upload</button>


document.getElementById('button').addEventListener('click', function() {
  var files = document.getElementById('file').files;

  var reader = new FileReader();
   reader.readAsDataURL(files);
   reader.onload = function () {
     console.log(reader.result);
    alert('my file: ' +reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   }

});
2
  • 1
    files property is a FileList (an array like structure), you need to access and pass the individual file objects in that list, eg readAsDataURL(files[0]) Commented Jun 12, 2020 at 11:35
  • Thanks @Patrick Evans, its working now. you can update it as the right answer Commented Jun 12, 2020 at 12:08

1 Answer 1

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

async function Main() {
   const file = document.querySelector('#myfile').files[0];
   console.log(await toBase64(file));
}

Main();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.