5

I want to convert an local image to base64. The reader.readAsDataURL does not work. I always get an undefined for the rawImg var. The value for the file var, are the metadata from the file I try to upload. enter image description here

HTML:

<input
  type="file"
  accept="image/jpeg/*"
  @change="uploadImage()"
/>

JS:

uploadImage() {
  const file = document.querySelector('input[type=file]').files[0]
  const reader = new FileReader()

  const rawImg = reader.readAsDataURL(file)
  console.log(file)
  console.log(rawImg)
}
Marcel Klein
  • 117
  • 1
  • 1
  • 9

1 Answers1

7

It won't work if you set the image directly from readAsDataURL, which returns undefined always. Instead, use the onloadend event:

let rawImg;
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();

reader.onloadend = () => {
   rawImg = reader.result;
   console.log(rawImg);
}
reader.readAsDataURL(file);
Dan
  • 59,490
  • 13
  • 101
  • 110