javascriptfile

Can't use forEach with Filelist


I'm trying to loop through a Filelist:

console.log('field:', field.photo.files)
field.photo.files.forEach(file => {
   // looping code
})

As you can see field.photo.files has a Filelist:

enter image description here

How to properly loop through field.photo.files?


Solution

  • A FileList is not an Array, but it does conform to its contract (has length and numeric indices), so we can "borrow" Array methods:

    Array.prototype.forEach.call(field.photo.files, function(file) { ... });
    

    Since you're obviously using ES6, you could also make it a proper Array, using the new Array.from method:

    Array.from(field.photo.files).forEach(file => { ... });