简体   繁体   中英

readAsDataURL - Get Image as Base64

I am loading an image using readAsDataURL like this...

 function previewFile() { console.log('Start Function')  var preview = document.querySelector('img');  var file    = document.querySelector('input[type=file]').files[0];  var reader  = new FileReader();  reader.addEventListener("load", function () {    preview.src = reader.result;  }, false);  if (file) {    reader.readAsDataURL(file);  } canvas = document.getElementById("preview"); imageData = canvas.toDataURL("image/jpeg"); console.log(imageData) } 
 <input type="file" onchange="previewFile()"><br> <img id="preview" src="https://dummyimage.com/600x400/000/fff" height="200" alt="Image preview..."> 

I am trying to get the previewed image as base64 data, I have tried to use toDataURL but it is returning an error.

Where am I going wrong?

Your HTML Element should be a canvas and not an image:

<input type="file" onchange="previewFile()"><br>
<canvas id="preview" height="200" />

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