How to iterate over FileList in JavaScript

In this article 👇

A FileList is an array-like object that represents a collection of File objects returned by the files property of the HTML <input> element. You can use this to access the list of files selected with the <input type="file"> element.

Just like a JavaScript array, FileList has the length property that returns the number of files in the list. However, it is not an actual array. So you can not use common array's methods like slice(), map(), filter(), or forEach() on a FileList object.

Let us say you have got the following HTML element:

<input type="file" id="avatars" multiple>

To loop through all the selected files with the above input element (a FileList object), you can use the classic for loop as shown below:

const input = document.querySelector('#avatars')

// Retrieve FileList boject
const files = input.files

// Loop through files
for (let i = 0; i < files.length; i++) {
  let file = files.item(i)
  console.log(file.name)
}

The item() method returns a File object representing the file at the specified index in the file list. You can also directly access the file using the index notation (files[i]).

Convert FileList to an array

When you convert a FileList object into an array, you can use all array methods like forEach(), map(), and filter().

There are multiple ways to convert a FileList to an array. I've already explained these methods in the NodeList to array conversion article.

The Array.from() is one such method that takes in an array-like object as input and returns an array:

const input = document.querySelector('#avatars')

// Retrieve FileList boject
const files = input.files

// Convert FileList to array
const arr = Array.from(files)

// Loop through an array
arr.forEach(file => console.log(file.name))

Alternatively, you could also spread operator syntax to convert a FileList to an array:

const arr = [...files]

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.