Created
November 9, 2015 04:28
-
-
Save kidatti/f93feba1ec4be2117d1b to your computer and use it in GitHub Desktop.
Upload clipboard image to server (HTML5 / JavaScript / AJAX)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
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
I have a question, what should I enter in the clipboard_js.php file?