Search code examples
javascripthtmlimagevue.jsbase64

Vue convert image into base64


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)
}

Solution

  • 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);