简体   繁体   中英

how to remove a file from file upload control before uploading it using jQuery

I am using a multi-file upload control to upload files. I am listing the files before I upload so users can see the names of file what are they uploading. I have a delete button in each file name row. I am trying to remove the file from the list when I click the remove button, just in case I changed my before I upload. I am running out of ideas on

 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>

how to do it?

here is my code

delete file function is where I am trying to do it.

From your code, I can see that you forget to remove the dom that why the file still exists.

Another, to make the code simple we can attach data-index inside the delete button to remember the file index when we're deleting it will be easy than compare the string of filename.

Here is the modified code.

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM