简体   繁体   中英

convert local image to base64 data

HTML code

<input id="file-input" accept="image/png, image/jpeg" type="file" name="name" />

after selecting the image , I run this code

var file = $("#file-input").val();
console.log(getBase64(file));

here's the getBase64 function

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

this function fires this error :

Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

that's what I tried - if you have workable answer = please share it

Try changing

var file = $("#file-input").val();

to

var file = $("#file-input")[0].files[0];

.val() is not actually returning the blob/file object that you want in this case.

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