How to append files in input type file with multiple before uploading

Aisha picture Aisha · Apr 3, 2014 · Viewed 23.4k times · Source

I select 2 images and again I select 3 images second time before upload, the first two gets removed from input type file and last 3 images are still there. I know it's the default behavior of input type file, that it replaces the new files with new selected ones, but I want to keep all the files user selects multiple times before upload. How is it possible? I am using ajax and formdata.

Answer

Uday A. Navapara picture Uday A. Navapara · May 20, 2014

I have face same problem like you

now i have found solution for that

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

this is working in my page properly i wish this is also be useful for you also