FileReader drags image from browser window

I have a div where users can drag and drop an image, and then using FileReader, I get base64 images. It works great.

dropper.ondrop = function (e) { e.preventDefault(); var file = e.dataTransfer.files[0]; var reader = new FileReader(); reader.readAsDataURL(file); }; 

My problem is that if I have a browser window open and drag the image from the browser, I get an error message:

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

Now, is there any twist to get the base64 image being dragged from the browser window?

Ultimately, is there a way to get the image url and then the actual base64 with the server side curl request?

Any idea?

+5
source share
2 answers

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/

+1
source

The first parameter comes using the protocol "http: //" or "https: //" instead of the expected file ": //" . and therefore you cannot read it using the HTML5 FILE API , so you can first download and save the file before trying to read the contents. on the other hand, you can update the src attribute of the img tag with the extracted URL and skip the readDataAsUrl () part for the hotlink image.

0
source

Source: https://habr.com/ru/post/1272095/


All Articles