alex
alex

Reputation: 7601

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?

Upvotes: 290

Views: 149017

Answers (8)

Mir-Ismaili
Mir-Ismaili

Reputation: 16948

Use for...of loop:

for (const file of fileList) {
  // ...
}

Upvotes: 4

dude
dude

Reputation: 6086

In ES6 you can use:

[...field.photo.files].forEach(file => console.log(file));

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Upvotes: 60

user11164708
user11164708

Reputation: 29

from https://developer.mozilla.org/en-US/docs/Web/API/FileList

  for (const file of fileInput.files) {
    output.innerText += `\n${file.name}`;
  }

in this case

  for (const file of field.photo.files) {
    //some code
  }

Upvotes: 2

Victor Hugo Arango A.
Victor Hugo Arango A.

Reputation: 159

If you are using Typescript you can do something like this: For a variable files with a type FileList[] or File[] use:

for(let file of files){
    console.log('line50 file', file);
}

Upvotes: -7

Shalabh Shankhdhar
Shalabh Shankhdhar

Reputation: 39

The following code is in Typescript

urls = new Array<string>();

detectFiles(event) {
   const $image: any = document.querySelector('#file');
   Array.from($image.files).forEach((file: any) => {
      let reader = new FileReader();
      reader.onload = (e: any) => { this.urls.push(e.target.result); }
      reader.readAsDataURL(file);
   }
}

Upvotes: 3

Mohoch
Mohoch

Reputation: 2691

The lodash library has a _forEach method that loops through all collection entities, such as arrays and objects, including the FileList:

_.forEach(field.photo.files,(file => {
     // looping code
})

Upvotes: 6

Willian Ribeiro
Willian Ribeiro

Reputation: 755

You can also iterate with a simple for:

var files = field.photo.files;

for (var i = 0; i < files.length; i++) {
    console.log(files[i]);
}

Upvotes: 64

Amadan
Amadan

Reputation: 198324

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 => { ... });

Upvotes: 471

Related Questions