Note that there are some explanatory texts on larger screens.

plurals
  1. POCorruption with FileReader into FormData
    text
    copied!<p>I'm building an ajax file uploader, which is possible thanks to the new <a href="https://developer.mozilla.org/en/DOM/XMLHttpRequest/FormData" rel="nofollow">FormData</a> interface. It works if I use the original file, but if I convert the file to a binary string and then to a blob, the resulting file is corrupted. What am I doing wrong?</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;form method=post enctype=multipart/form-data id=form&gt; &lt;input id=file type=file name=file&gt; &lt;button id=1&gt;1&lt;/button&gt; &lt;button id=2&gt;2&lt;/button&gt; &lt;/form&gt; &lt;script&gt; var d = document; function $(id) { return d.getElementById(id); }; function xhr(fd) { var x = new XMLHttpRequest(); x.open('post', '/', true); x.send(fd); }; $(1).addEventListener('click', function(e) { e.preventDefault(); var file = $('file').files[0]; var fd = new FormData(); fd.append('file', file); xhr(fd); }, false ); $(2).addEventListener('click', function(e) { e.preventDefault(); var file = $('file').files[0]; var fr = new FileReader(); fr.onload = function(e) { var bb = new (window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder)() bb.append(e.target.result); var b = bb.getBlob(file.type); var fd = new FormData(); fd.append('file', b); xhr(fd); }; fr.readAsBinaryString(file); }, false ); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><a href="https://developer.mozilla.org/en/DOM/Blob" rel="nofollow">Blob</a> <a href="https://developer.mozilla.org/en/DOM/BlobBuilder" rel="nofollow">BlobBuilder</a> <a href="https://developer.mozilla.org/en/DOM/FileReader" rel="nofollow">FileReader</a> <a href="https://developer.mozilla.org/en/DOM/XMLHttpRequest/FormData" rel="nofollow">FormData</a></p> <p>edited to include links</p>
 

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