How to upload an image through the clipboard (copy and paste)?

2

I was taking a look at the functionality of Imgur site. When you make a printscreen or even copy an image (not the link, but the image, which is an option that is available in most current browsers) and then paste on the page, the image that was saved is uploaded in the clipboard.

I have no idea how Javascript can access that part of the memory where the "Copy" was saved.

I would like a simple demonstration of how I can do to transfer the image from memory and send it through upload. I would also like to know if it is possible to transfer the contents of the Clipboard (CTRL + C) to a Javascript Blob.

    
asked by anonymous 09.01.2018 / 14:27

1 answer

5

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

    
09.01.2018 / 15:06