Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to receive php image data over copy-n-paste javascript with XMLHttpRequest
    primarykey
    data
    text
    <p>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.</p> <p>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:</p> <pre><code> 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); } </code></pre> <p>The handling php (<code>php/image-upload.php</code>) looks like that:</p> <pre><code>$base64string = $_POST['file']; file_put_contents('img.png', base64_decode($base64string)); </code></pre> <p>I think the <code>$_POST['file']</code> 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.</p> <p>The developer console displays this.</p> <pre><code>{"0":{"type":"text/plain","kind":"string"},"1":{"type":"image/png","kind":"file"},"length":2} image-upload.js:8 Blob {type: "image/png", size: 135619, slice: function} </code></pre> <p>If I view the file-info by right-clicking the actual image file, it shows <code>5,320 bytes (8 KB on disk)</code> in size.</p> <p>I do not necessarily need to use a <code>XMLHttpRequest</code>, 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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload