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.