Note that there are some explanatory texts on larger screens.

plurals
  1. POAssign file as value of hidden input
    text
    copied!<p>I am using a multiple file upload field <code>&lt;input name="filesToUpload" id="filesToUpload" type="file" multiple /&gt;</code> in my app. </p> <p>What I want to accomplish is to list the files the users chose and than allow them to delete any of them in the list. At the end, when the form is submitted, I send the whole data via AJAX, as binary, using the <code>FormData</code> object.</p> <p>It all works great, except for the delete part.</p> <p>I know that the <code>FileList</code> attribute is read-only, so what I did was to distribute the files as values of hidden input fields, appended to each of the <code>li</code> where I list the file names. So if the user removes a <code>li</code> item, the hidden input field is gone with it, and at the end, I collect all remaining by appending them to the <code>FormData</code> object.</p> <p>Problem is, every attempt I made to assign the files as values to the hidden inputs gave me weird results.</p> <p>My code is something like this:</p> <pre><code>listFiles : function () { var file, files, filesList, filesLength, read; files = this.files; filesList = $('.files'); filesLength = files.length; // Clear the list filesList.html(''); for ( var i = 0; i &lt; filesLength; i++ ) { file = files[i]; // This is to read the content of the file read=new FileReader(); read.readAsBinaryString( file ); // When reading is finished read.onloadend = function() { filesList.append( '&lt;li&gt;' + '&lt;span class="fileName"&gt;' + file.name + '&lt;/span&gt;' + '&lt;a href="#" class="deleteAttachment"&gt;x&lt;/a&gt;' + '&lt;input type="hidden" name="file[]" value="' + read.result +'"/&gt;' + '&lt;/li&gt;'); } } } </code></pre> <p>I just get the data from the last file, also, the DOM is broken since the data gets printed all over the place.</p> <p>Demo here => <a href="http://jsfiddle.net/zKyXC/" rel="nofollow">http://jsfiddle.net/zKyXC/</a></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