When something is pasted to a page, js
triggers an event in the onpaste .
When we paste an image, js
through the function onpaste
returns us an object with the interface (Only in the case of binaries, obvious) . With this object, we can use the getAsFile()
method that we will use with the FileReader
class.
To read this content, we can use the readAsDataURL
method of the class FileReader . With this we are able to capture the% code of% of the image, and this is basically what the site code does. It basically sends a base64
, rather than a file, to the server.
Here's a simple example.
var reader = new FileReader();
reader.onload = function(result) {
let img = document.createElement("img");
img.src = result.target.result;
document.body.appendChild(img);
}
document.querySelector("input").onpaste = function(event){
let items = event.clipboardData.items;
for (itemIndex in items) {
let item = items[itemIndex];
if (item.kind == 'file') {
reader.readAsDataURL(item.getAsFile());
}
}
}
<input type="text" placeholder="Cole sua imagem aqui" />
Errata: Why does Javascript need a base64
to find the image?
for
needs this js
because when you copy an image from the internet, it is casting an action on for
with two DataTransferItem .
The first item is a onpaste
code with a html
element. In this element we receive a code <img>
or the URL of the image. So you're getting a base64
(You can also get a text/html
) .
The second is already an image in itself. Can be captured using the text/plain
method