You can use e.dataTransfer.getData('url') to find out if the URL is accessible. Like this:
var url = e.dataTransfer.getData('url'); if(url){ console.log('Url'); console.log(url); }else{ console.log('File'); var file = e.dataTransfer.files[0]; var reader = new FileReader(); reader.readAsDataURL(file); }
Then, with the URL, you can load the img element and use it on canvas to capture the base64 view. Like this:
var img = document.createElement('img'); img.crossOrigin = 'anonymous'; img.onload = function(){ var canvas = document.createElement('canvas'); canvas.width = this.width; canvas.height = this.height; var context = canvas.getContext('2d'); context.drawImage(this, 0, 0); console.log(canvas.toDataURL()); }; img.src = url;
This will be the βfinalβ product:
var dropper = document.querySelector('div'); dropper.ondragover = function(e) { e.preventDefault(); } dropper.ondrop = function (e) { e.preventDefault(); var url = e.dataTransfer.getData('url'); if(url){ console.log('Url'); console.log(url); var img = document.createElement('img'); img.crossOrigin = 'anonymous'; img.onload = function(){ var canvas = document.createElement('canvas'); canvas.width = this.width; canvas.height = this.height; var context = canvas.getContext('2d'); context.drawImage(this, 0, 0); console.log(canvas.toDataURL()); }; img.src = url; }else{ console.log('File'); var file = e.dataTransfer.files[0]; var reader = new FileReader(); reader.readAsDataURL(file); } };
div{ border:1px solid red; height:240px; width:100%; }
<div>Drop here</div>
Also available here: https://jsfiddle.net/8u6Lprrb/1/
Piyin source share