【问题标题】:How to append files in input type file with multiple before uploading [closed]如何在上传之前在输入类型文件中附加多个文件[关闭]
【发布时间】:2014-05-15 16:16:28
【问题描述】:

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

【问题讨论】:

标签: html form-data html-input


【解决方案1】:

我也遇到了和你一样的问题

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

 <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>

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

【讨论】:

  • 非常感谢您的回答,我会尝试这个解决方案。谢谢
  • 您的回答似乎有错误。这行$("input[name=replyfiles]").val(storedFiles); 抛出错误,因为输入类型的文件不能通过 Javascript 进行修改。只有重置它才能工作。
  • 同样&lt;div id="#filelist"&gt;&lt;/div&gt; 应该是&lt;div id="filelist"&gt;&lt;/div&gt;
【解决方案2】:

正确的方法是使用 $("input[name=replyfiles]").clone().appendTo( $("input[name=replyfiles]").parent() ).val(''); $("input[name=replyfiles]").hide(); 除了$("input[name=replyfiles]").val(storedFiles);

【讨论】:

  • 投了反对票,因为你没有格式化你的代码,也没有解释你做了什么。
猜你喜欢
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
  • 2012-10-12
  • 2013-12-24
  • 2017-03-21
  • 2021-02-18
  • 2014-10-23
  • 1970-01-01
相关资源
最近更新 更多