Marcel Klein
Marcel Klein

Reputation: 127

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

Upvotes: 5

Views: 15798

Answers (2)

ariel acha
ariel acha

Reputation: 37

Same concept as above but a tad bit shorter approach.

<input type="file" @change="createImage" />

function createImage(file) {
    const reader = new FileReader();
    reader.onloadend = () => (console.log(reader.result));
    reader.readAsDataURL(file.target.files[0]);
}

Upvotes: 0

Dan
Dan

Reputation: 63139

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

Upvotes: 8

Related Questions