2

Currently my codes is the same as the one from here: How to display selected file names before uploading multiple files in Struts2?

How do I convert file list to array and add a remove link next to each file names and remove it before upload?

Thanks.

Matt
  • 199
  • 1
  • 1
  • 9

2 Answers2

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();
}
Chand Ra
  • 69
  • 6
  • Thanks for helping out Chand Ra, what about the remove link that need to initiate that sweet remove function that you coded? How do i add remove link next to the file names? – Matt Nov 27 '18 at 07:30
1

I would do this using recursive function. See the solution below:

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>
Parn
  • 878
  • 7
  • 19