目前,我的代码与此处的代码相同:How to display selected file names before uploading multiple files in Struts2?
如何将文件列表转换为数组,并在每个文件名旁边添加删除链接,并在上传之前将其删除?
谢谢。
答案 0 :(得分:1)
<input type="file" id="file" multiple>
<ul id="list"></ul>
let file=document.getElementById("file");
let list=document.getElementById("list");
let fileList=[];
file.addEventListener("change",(e)=>{
Array.prototype.forEach.call(e.target.files,(file)=>{
fileList.push(file);
});
updateList();
});
function updateList(){
list.innerHTML="";
fileList.forEach((file)=>{
let li=document.createElement("li");
li.innerHTML="<span>"+file.name+"</span><a href='javascript:void(0)' class='remove'>remove</a>";
list.appendChild(li);
});
}
list.addEventListener("click",(e)=>{
let target=e.target;
if(target.className=="remove"){
let parent=target.parentNode;
let fileName=parent.children[0].innerText;
refreshList(fileName);
}
});
function refreshList(fileName){
fileList=fileList.filter((file)=>{
return file.name.indexOf(fileName)==-1;
});
console.log(fileList);
updateList();
}
答案 1 :(得分:1)
我将使用递归函数执行此操作。请参阅下面的解决方案:
function updateList () {
var input = document.getElementById('file');
// Create list or array
var list = [];
for (var i = 0, len = input.files.length; i < len; ++i) {
list.push(input.files.item(i));
}
// Output file list
outputList(list);
}
function outputList (list) {
var output = document.getElementById('fileList');
while (output.hasChildNodes()) {
output.removeChild(output.lastChild);
}
var nodes = document.createElement('ul');
for (var i = 0, len = list.length; i < len; ++i) (function(i) {
var node = document.createElement('li');
var filename = document.createTextNode(list[i].name);
var removeLink = document.createElement('a');
removeLink.href = 'javascript:void(0)';
removeLink.innerHTML = 'Remove';
removeLink.onclick = function () {
// Remove item
list.splice(i, 1);
outputList(list);
}
node.appendChild(filename);
node.appendChild(removeLink);
nodes.appendChild(node);
})(i);
output.appendChild(nodes);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="file" id="file" multiple
onchange="javascript:updateList()" />
<br/>Selected files:
<div id="fileList"></div>