Skip to content

Instantly share code, notes, and snippets.

@kidatti
Created November 9, 2015 04:28
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save kidatti/f93feba1ec4be2117d1b to your computer and use it in GitHub Desktop.
Save kidatti/f93feba1ec4be2117d1b to your computer and use it in GitHub Desktop.
Upload clipboard image to server (HTML5 / JavaScript / AJAX)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<script>
document.onpaste = function(event){
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
for (var i = 0 ; i < items.length ; i++) {
var item = items[i];
if (item.type.indexOf("image") != -1) {
var file = item.getAsFile();
console.log(file);
upload_file_with_ajax(file);
}
}
}
function upload_file_with_ajax(file){
var formData = new FormData();
formData.append('file', file);
$.ajax('./clipboard_js.php' , {
type: 'POST',
contentType: false,
processData: false,
data: formData,
error: function() {
console.log("error");
},
success: function(res) {
console.log("ok");
}
});
}
</script>
</body>
</html>
@darek3444
Copy link

I have a question, what should I enter in the clipboard_js.php file?

@brainexcerpts
Copy link

Something along those line could be used:

// minimal example of clipboard_js.php
// Very unsafe, at the very least it would be better safeguard and check file name, file type etc. 

// HTTP headers for no cache etc
header('Content-type: text/plain; charset=UTF-8');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");


if(isset($_FILES['file'])) {
    // File upload directory

    // Get the filename
    $target_file = basename($_FILES["file"]["name"]);

    // Move the file to the uploads directory
    if (! move_uploaded_file($_FILES["file"]["tmp_name"], $targetDir. DIRECTORY_SEPARATOR . $target_file)) {
        // Error uploading file
        echo "Sorry, there was an error uploading your file.";
    }
    exit();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment