File field - Append file list

Lanbo picture Lanbo · May 24, 2013 · Viewed 17.8k times · Source

I have made me a simple file field:

<input type="file" name="pictures_array[]" multiple accept="image/*" id="page_pictures_array" />

and some HTML5 File API code to list the files:

$('.page-form #page_pictures_array').change(function(evt) {
      var file, files, reader, _i, _len;
      files = evt.target.files;
      console.log(files);
      $('#file-list').empty();
      for (_i = 0, _len = files.length; _i < _len; _i++) {
        file = files[_i];
        reader = new window.FileReader;
        reader.onload = (function(file) {
          return function(e) {
            var src;
            src = e.target.result;
            return $("<li>" + file.name + " - " + file.size + " bytes</li>").prepend($('<img/>', {
              src: src,
              "class": 'thumb'
            })).appendTo($('#file-list'));
          };
        })(file);
        reader.readAsDataURL(file);
      }
    });

(cf. here)

However, since I expect my users to be very stupid indeed, I am sure they will choose one file, then click on the upload field another time to choose the next. However, the list of the <input type="file"> is reset each time with the newly chosen images.

How can I make sure the new files are appended to the <input>'s array so I don't get flooded with angry user comments?

Answer

miguelmpn picture miguelmpn · Jan 28, 2014

I'm also looking for an answer to this, I think others already do that. But if you look at the filelist W3 reference http://www.w3.org/TR/FileAPI/#dfn-filelist it says that its readonly....

Edit: It's a big code now, with some improvements, that make the copy/paste difficult. But I started to create one variable that saves all the tmp files.

var tmp_files = new Array();

Then when I add a new file I push the file to that array like this

tmp_files.push(file);

After all the insertions/removals (I have another var to save the deletions) when the user clicks to send the files I have this code that makes the formdata with the files I want

var data = new FormData(); var count = 0;
$.each(tmp_files, function(i, file){
    if(del_files.indexOf(file.name)== -1){
        data.append(count, file);
        count++;
    }
});

Then I just send the var data thru ajax and save them. You can get them using $data = $_FILES;

Hope this helps you.