【问题标题】:Need to remove specific file from html file input with multiple selection enabled需要在启用多项选择的情况下从 html 文件输入中删除特定文件
【发布时间】:2016-02-21 03:47:41
【问题描述】:

我有一个文件输入字段,我可以在其中一次选择多个文件,并在具有特定文件删除功能的列表中显示所有选定的文件。现在我可以从列表中删除文件,但我找不到从输入字段数组中删除文件的方法。如何使用 jQuery 从输入字段数组中删除特定文件。 我不想为此使用任何插件。

$('#uploadBtn').change(function(){
  $('#attachments').html('');
  var attachments = document.getElementById('uploadBtn');
  var item = '';
  for(var i=0; i<attachments.files.length; i++) {
    item += '<li>' + attachments.files.item(i).name +
      '&nbsp;&nbsp;<a href="#" id="'+ i +'" class="dlt-attch">Remove</a>' +
      '</li>';
    console.log(attachments.files.item(i).name);
  }
  $('#attachments').append(item);
  $('.dlt-attch').click(function(e){
    e.preventDefault();
    var id = $(this).attr('id');
    console.log(attachments.files);
    $(this).parent().remove();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="uploadBtn" multiple="multiple" type="file" name="attachments[]" class="upload" />
<ul id="attachments" style="margin-top: 10px; list-style-type: decimal;"></ul>

【问题讨论】:

标签: javascript jquery html file input


【解决方案1】:

很遗憾,您无法从该列表中删除文件,因为它们存储在只读FileList 对象中:https://developer.mozilla.org/en-US/docs/Web/API/FileList

作为替代方案,您可以保留自己的文件数组,但您需要使用自己的实现来上传文件。

几年前有人问过一个类似的问题,但它仍然有效: How do I remove a file from the FileList - 有一个答案是使用XMLHttpRequest 手动上传文件。

【讨论】:

    猜你喜欢
    • 2014-10-16
    • 2014-07-29
    • 2017-07-15
    • 2018-04-07
    • 2020-04-10
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多