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

I was taking a look at the functionality of the site Imgur. 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, it is uploaded the image that was saved on the clipboard (clipboard).

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

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

Author: Wallace Maxters, 2018-01-09

1 answers

When something is pasted to a page, js fires an event in the function onpaste.

When we paste an image, the js through the function onpaste returns us an object with the interface files (only in the case of binaries, obvious) . With this object, we can use the method getAsFile() that we will use with the Class FileReader.

To read this content, we can use the readAsDataURL method of the class FileReader. With this we were able to capture the base64 code of the image, and that's basically what the site code does. It basically sends a base64, rather than a file, to the server.

Follows 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" />

Incorrect: Why does Javascript need a for to find the image?

js needs that for because when you copy an image from the internet, it is launching an action on onpaste with two DataTransferItem.

The first item is a code html with an element <img>. In this element we receive a code base64 or the URL of the image. So you are getting a text/html (you can also receive a text/plain).

The second, it is already an image itself. Can be captured using the method DataTransferItem.getAsFile()

 5
Author: Valdeir Psr, 2018-01-12 22:15:53