File field - Append file list

我与影子孤独终老i 提交于 2019-12-09 20:45:03

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/16742956/file-field-append-file-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!