Need to remove specific file from html file input

2019-06-09 08:02发布

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>

1条回答
Rolldiameter
2楼-- · 2019-06-09 08:38

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.

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.

查看更多
登录 后发表回答