需要从启用了多个选择的html文件输入中删除特定文件 [英] Need to remove specific file from html file input with multiple selection enabled

查看:95
本文介绍了需要从启用了多个选择的html文件输入中删除特定文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a file input field where I can select multiple files at once, and show all the selected files in a list with specific file removal functionality. Now I can remove the file from the list, but I couldn't find a way to remove the file also from the input field array. How can I remove the specific file from input field array too using jQuery. I don't want to use any plugin for this.

$('#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>

推荐答案

不幸的是,您无法从该列表中删除文件,因为它们存储在只读 FileList 对象中:< a href =https://developer.mozilla.org/en-US/docs/Web/API/FileList\"rel =nofollow noreferrer> https://developer.mozilla.org/en-US/docs/Web / API / FileList

Unfortunately you can't remove a file from that list because they are stored in a read-only FileList object: https://developer.mozilla.org/en-US/docs/Web/API/FileList

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

As an alternative you can keep your own array of files, but then you will need to use your own implementation to upload the files.

几年前有一个类似的问题,但它仍然有效:
如何从FileList中删除文件 - 有一个答案使用 XMLHttpRequest 手动上传文件。

There is a similar question that was asked a few years ago but it is still valid: How do I remove a file from the FileList - There is an answer that uses XMLHttpRequest to manually upload the files.

这篇关于需要从启用了多个选择的html文件输入中删除特定文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆