When something is pasted on a page, the js
fires an event in function onpaste.
When we paste an image, the js
through function onpaste
returns an object with the interface File (Only in the case of binaries, obvious). With this object, we can use the method getAsFile()
which we will use with the class FileReader
.
To read this content, we can use the method readAsDataURL
class Filereader. With that we can capture the code base64
image, and that’s basically what the site code does. It basically sends a base64
, instead of a file, to the server.
Follow a very 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 Javascript Needs a for
to find the image?
The js
needs this for
because when you copy an image from the internet, it’s launching an action on onpaste
with two Datatransferetes.
The first item is a code html
with an element <img>
. In this element we receive a code base64
or the image URL. That’s why you’re getting a text/html
(You can also receive one text/plain
).
The second is already an image itself. It can be captured through the method DataTransferItem.getAsFile()
Nice, man. Simple and direct. + 1
– Wallace Maxters
I only have one question: Why Javascript needs a
for
to find the image? Strangely in a code I made similar to yours, the value0
of iteration always brings aitem
with the valuetext/html
in thetype
or empty, kkkkk...– Wallace Maxters
When you copy a file from the web, instead of looking at the binary, it looks like html. I made a change that "circumvents" this.
– Valdeir Psr
Unconvinced with my code, I did some more research and, doing some additional testing, found a "decent" answer to the above question.
– Valdeir Psr
@Bacco, in the previous edition I forgot to change
srcElement.target.result;
forresult.target.result;
. Corrected. = D– Valdeir Psr