如何在上传之前在多个输入类型文件中附加文件

Ais*_*sha 8 html form-data html-input

我选择2张图片并再次在上传前第二次选择3张图片,前两张图片从输入类型文件中删除,最后3张图片仍在那里.我知道这是输入类型文件的默认行为,它用新选择的文件替换新文件,但我想保留用户在上传之前多次选择的所有文件.这怎么可能?我正在使用ajax和formdata.

Uda*_*ara 4

我面临着和你一样的问题

现在我已经找到了解决方案

 <input type="file" id="attachfile" name="replyFiles" multiple> <!--File Element for multiple intput-->
 <div id="#filelist"></div>
 <script>
    var selDiv = "";
    var storedFiles = []; //store the object of the all files

    document.addEventListener("DOMContentLoaded", init, false); 

    function init() {
       //To add the change listener on over file element
       document.querySelector('#attachfile').addEventListener('change', handleFileSelect, false);
       //allocate division where you want to print file name
       selDiv = document.querySelector("#filelist");
    }

    //function to handle the file select listenere
    function handleFileSelect(e) {
       //to check that even single file is selected or not
       if(!e.target.files) return;      

       //for clear the value of the selDiv
       selDiv.innerHTML = "";

       //get the array of file object in files variable
       var files = e.target.files;
       var filesArr = Array.prototype.slice.call(files);

       //print if any file is selected previosly 
       for(var i=0;i<storedFiles.length;i++)
       {
           selDiv.innerHTML += "<div class='filename'> <span> " + storedFiles[i].name + "</span></div>";
       }
       filesArr.forEach(function(f) {
           //add new selected files into the array list
           storedFiles.push(f);
           //print new selected files into the given division
           selDiv.innerHTML += "<div class='filename'> <span> " + f.name + "</span></div>";
       });

       //store the array of file in our element this is send to other page by form submit
       $("input[name=replyfiles]").val(storedFiles);
 }
 </script>
Run Code Online (Sandbox Code Playgroud)

这在我的页面中正常工作我希望这对您也有用

  • 您的回答似乎有错误。这行 `$("input[name=replyfiles]").val(storedFiles);` 会抛出错误,因为无法通过 Javascript 修改输入类型文件。只有重新设置才能起作用。 (7认同)