5

I'm trying to get an image from clipboard in javascript following this post: https://stackoverflow.com/a/6338207/6188783

document.onpaste = function (event) {
    console.log("paste triggered!");
    console.log("text: " + event.clipboardData.getData("text")); // shows text if it was pasted
    console.log("image: " + event.clipboardData.getData("image")); // always returns empty string p.s. I've also tried image/bmp and other formats 
    var items = (event.clipboardData || event.originalEvent.clipboardData).items;
    console.log(JSON.stringify(items)); // will give you the mime types
    for (index in items) {
        var item = items[index];
        if (item.kind === 'file') {
            var blob = item.getAsFile();
            var reader = new FileReader();
            reader.onload = function(event){
                console.log(event.target.result)}; // data url!
            reader.readAsDataURL(blob);
        }
    }
}

The issue is the clipboardData.items and clipboardData.files are always empty for files. When I'm pasting some text, it can be found in items array. Some guys from comments say that this answer is not working for new browsers, but I was not able to find how it can be done now. Please help!

Thanks in advance!

UPDATE

I figured out that the image is not getting handled when it's copied from i.e. folder. If I copy image from i.e. paint it is pushed into items array. How can I handle the image file copied from windows explorer then?

Nikita Fedorov
  • 790
  • 1
  • 12
  • 40
  • 1
    I am doing something similar and tried what happened when I copy a file from my desktop. It seems it will not be recognised. My best guess is that it is not intended or supported to copy files and paste them. The only way right now is to either use input form where you can choose the file or using drag and drop. You can even drag and drop directories. We just can hope that pasting files will be added as feature at some point. – Tom-Oliver Heidel Jun 12 '19 at 16:20
  • I know it's old and not the answer to the question but it might help out using drag'n'drop therefore – René Baudisch May 18 '20 at 13:03

0 Answers0