Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Uploading files is actually possible with AJAX these days. Yes, AJAX, not some crappy AJAX wannabes like swf or java.</p> <p>This example might help you out: <a href="https://webblocks.nl/tests/ajax/file-drag-drop.html" rel="noreferrer">https://webblocks.nl/tests/ajax/file-drag-drop.html</a></p> <p>(It also includes the drag/drop interface but that's easily ignored.)</p> <p>Basically what it comes down to is this:</p> <pre><code>&lt;input id="files" type="file" /&gt; &lt;script&gt; document.getElementById('files').addEventListener('change', function(e) { var file = this.files[0]; var xhr = new XMLHttpRequest(); (xhr.upload || xhr).addEventListener('progress', function(e) { var done = e.position || e.loaded var total = e.totalSize || e.total; console.log('xhr progress: ' + Math.round(done/total*100) + '%'); }); xhr.addEventListener('load', function(e) { console.log('xhr upload complete', e, this.responseText); }); xhr.open('post', '/URL-HERE', true); xhr.send(file); }); &lt;/script&gt; </code></pre> <p>(demo: <a href="http://jsfiddle.net/rudiedirkx/jzxmro8r/" rel="noreferrer">http://jsfiddle.net/rudiedirkx/jzxmro8r/</a>)</p> <p>So basically what it comes down to is this =)</p> <pre><code>xhr.send(file); </code></pre> <p>Where <code>file</code> is typeof <code>Blob</code>: <a href="http://www.w3.org/TR/FileAPI/" rel="noreferrer">http://www.w3.org/TR/FileAPI/</a></p> <p>Another (better IMO) way is to use <code>FormData</code>. This allows you to 1) name a file, like in a form and 2) send other stuff (files too), like in a form.</p> <pre><code>var fd = new FormData; fd.append('photo1', file); fd.append('photo2', file2); fd.append('other_data', 'foo bar'); xhr.send(fd); </code></pre> <p><code>FormData</code> makes the server code cleaner and more backward compatible (since the request now has the exact same format as normal forms).</p> <p>All of it is not experimental, but very modern. Chrome 8+ and Firefox 4+ know what to do, but I don't know about any others.</p> <p>This is how I handled the request (1 image per request) in PHP:</p> <pre><code>if ( isset($_FILES['file']) ) { $filename = basename($_FILES['file']['name']); $error = true; // Only upload if on my home win dev machine if ( isset($_SERVER['WINDIR']) ) { $path = 'uploads/'.$filename; $error = !move_uploaded_file($_FILES['file']['tmp_name'], $path); } $rsp = array( 'error' =&gt; $error, // Used in JS 'filename' =&gt; $filename, 'filepath' =&gt; '/tests/uploads/' . $filename, // Web accessible ); echo json_encode($rsp); exit; } </code></pre>
 

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