如何在使用jQuery上传文件之前从文件上传控件中删除文件

问题描述

我正在使用多文件上传控件来上传文件。 我在上传之前会列出文件,以便用户可以看到他们上传文件名。 每个文件名行中都有一个删除按钮。 当我单击“删除”按钮时,我试图从列表中删除文件,以防万一在上载之前更改了我的文件。 我的想法没了

              
              var fileInput = document.getElementById('inputfile');
              var fileListdisplay = document.getElementById('allfiles');
              
              var fileList = [];
              var renderFileList,sendFile;
              
              fileInput.addEventListener('change',function (evnt) {
                    fileList = [];
                for (var i = 0; i < fileInput.files.length; i++) {
                    fileList.push(fileInput.files[i]);
                }
                renderFileList();
              });
              
              renderFileList = function () {
                fileListdisplay.innerHTML = '';
                fileList.forEach(function (file,index) {
                    var filedisplayEl = document.createElement('p');
                  filedisplayEl.innerHTML = file.name +"<div class=deletfile></div>";
                  fileListdisplay.appendChild(filedisplayEl);
                });
              };  
            
            
            $(document).on('click','.deletfile',function()
             {  
              var filen=($(this).parent().text());
               console.log(fileList);
              
              const index = fileList.indexOf(filen);
              console.log(index,filen);
                if (index > -1) {
                  fileList.splice(index,1);
                }
                
                //console.log(fileList);
             });
<input id="inputfile" type="file" multiple> <br><div id='allfiles'></div>

怎么做?

这是我的代码

删除文件功能是我要尝试的地方。

解决方法

从您的代码中,我可以看到您忘记删除文件仍然存在的dom。

另外,为了简化代码,我们可以在删除按钮内附加data-index来记住文件索引,而不是比较文件名字符串。

这是修改后的代码。

var fileInput = document.getElementById('inputfile');
var fileListDisplay = document.getElementById('allfiles');

var fileList = [];
var renderFileList,sendFile;

fileInput.addEventListener('change',function (evnt) {
  fileList = [];
  for (var i = 0; i < fileInput.files.length; i++) {
    fileList.push(fileInput.files[i]);
  }
  renderFileList();
});

renderFileList = function () {
  fileListDisplay.innerHTML = '';
  fileList.forEach(function (file,index) {
    var fileDisplayEl = document.createElement('p');
    fileDisplayEl.innerHTML = `${file.name} <button data-index="${index}" class='deletfile'>X</button>`;
    fileListDisplay.appendChild(fileDisplayEl);
  });
};


$(document).on('click','.deletfile',function()
{
  const index= $(this).attr('data-index');
  fileList.splice(parseInt(index,10),1);
  $(this).parent().remove();
});