Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add to an existing FileList object with JavaScript?

Tags:

javascript

I am creating a drag and drop file upload zone. When I upload multiple files at a time it works but I need it to be able to support uploading in multiple stages. I know that the issue below is that I am setting files each time, but I can't figure out the right way to get more files added to dFiles each time the method is called

    var dFiles;
    //var dFiles = []
    var holder = document.getElementById('holder');
    holder.ondrop = function (e) {
        e.preventDefault();
        dFiles = (e.dataTransfer.files);
        //dFiles.push(e.dataTransfer.files);
   }

I tried initilaizing dfiles as an empty array and adding the files (commented out above). Later this created a data type mismatch error when I was reading the file data

for (var i = 0; i < dFiles.length; i++) {
    reader = new FileReader();
    reader.readAsDataUrl(dFiles[i]); //error
}
like image 844
cooper Avatar asked May 24 '17 16:05

cooper


1 Answers

e.dataTransfer.files is a list of files.

You will have to add each file separately to dFiles:

var files = e.dataTransfer.files;

for (var i = 0, l = files.length; i < l; i++) {
    dFiles.push(files[i]);
}

Or the ES6 way:

dFiles.push(...e.dataTransfer.files);
like image 177
Andreas Avatar answered Sep 17 '22 18:09

Andreas