[英]how to remove a file from file upload control before uploading it using 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();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.