简体   繁体   中英

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. 在此处输入图像描述

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

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

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

let rawImg;
reader.onloadend = () => {
   rawImg = reader.result;
   console.log(rawImg);
}
reader.readAsDataURL(file);
console.log(file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM