I try to make an image-upload functionality similar to the one GMail uses. You copy (CTRL-C) an image from your desktop and paste (CTRL-V) it onto the website. The image is then uploaded via a XMLHttpRequest to a php-script that handles the incoming file, whereby "handling" means renaming and storing on the server.
I can already fetch the image (and -data), but I am unable to successfully submit and receive the XMLHttpRequest.My Javascript code looks like that:
document.onpaste = function(e){ var items = e.clipboardData.items; console.log(JSON.stringify(items)); if (e.clipboardData.items[1].kind === 'file') { // get the blob var imageFile = items[1].getAsFile(); console.log(imageFile); var reader = new FileReader(); reader.onload = function(event) { console.log(event.target.result); // data url! submitFileForm(event.target.result, 'paste'); }; } }; function submitFileForm(file, type) { var formData = new FormData(); formData.append('file', file); formData.append('submission-type', type); var xhr = new XMLHttpRequest(); xhr.open('POST', 'php/image-upload.php'); xhr.onload = function () { if (xhr.status == 200) { console.log('all done: '); } else { console.log('Nope'); } }; xhr.send(formData); }
The handling php (php/image-upload.php
) looks like that:
$base64string = $_POST['file'];file_put_contents('img.png', base64_decode($base64string));
I think the $_POST['file']
stays empty, but I am not sure.What's more, I also encounter the "blob size" (displayed with console.log()) is way larger than the actual image size. But maybe that's no matter or caused by encodings.
The developer console displays this.
{"0":{"type":"text/plain","kind":"string"},"1":{"type":"image/png","kind":"file"},"length":2} image-upload.js:8Blob {type: "image/png", size: 135619, slice: function}
If I view the file-info by right-clicking the actual image file, it shows 5,320 bytes (8 KB on disk)
in size.
I do not necessarily need to use a XMLHttpRequest
, it was just what came to my mind first. If there's a better way of achieving realtime image-uploading to a server with javascript, please let us know.