Удалить выбранное имя файла для ввода нескольких - PullRequest
0 голосов
/ 27 ноября 2018

В настоящее время мои коды совпадают с приведенными здесь: Как отобразить выбранные имена файлов перед загрузкой нескольких файлов в Struts2?

Как преобразовать список файлов в массив и добавитьудалить ссылку рядом с каждым именем файла и удалить его перед загрузкой?

Спасибо.

Ответы [ 2 ]

0 голосов
/ 27 ноября 2018

Я бы сделал это с помощью рекурсивной функции.Смотрите решение ниже:

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>
0 голосов
/ 27 ноября 2018
    <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();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...