Search code examples
jqueryfile-upload

Upload images from clipboard using jquery fileupload


I want to upload an image using ctrl + c or alt + PrtScr command and then paste inside a container or multiple containers for uploading them on server. I am using an existing JQuery function (included below), but I am unable to code it. Please show me the way.

$(function(){  
var btnUpload=$('#upload');  
var status=$('#status');  
new AjaxUpload(btnUpload, {  
    action: 'upload-file.php',  
    //Name of the file input box  
    name: 'uploadfile',  
    onSubmit: function(file, ext){  
        if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){   
              // check for valid file extension   
            status.text('Only JPG, PNG or GIF files are allowed');  
            return false;  
        }  
        status.text('Uploading...');  
    },  
    onComplete: function(file, response){  
        //On completion clear the status  
        status.text('');  
        //Add uploaded file to list  
        if(response==="success"){  
            $('<li></li>').appendTo('#files').html('<img src="./uploads/'+file+'" alt="" /><br />'+file).addClass('success');  
        } else{  
            $('<li></li>').appendTo('#files').text(file).addClass('error');  
        }  
    }  
});});

I will be grateful for any help provided.


Solution

  • Well, if you want to use the data in the clipboard you should check http://www.w3.org/TR/clipboard-apis/

    Basically, once you have got the data you´ll need a file interface to upload it.

    for example:

    file = item.getAsFile() -> Returns a File object
    

    So you need to handle the pasted data in a similar way to obtain the file interface.

    From: https://mobiarch.wordpress.com/2013/09/25/upload-image-by-copy-and-paste/

    function handlePaste(e) {
    for (var i = 0 ; i < e.clipboardData.items.length ; i++) {
        var item = e.clipboardData.items[i];
        console.log("Item type: " + item.type);
        if (item.type.indexOf("image") != -1) {
            uploadFile(item.getAsFile());
        } else {
            console.log("Discarding non-image paste data");
        }
    }