The FileList Object
By Flavio Copes
Learn what the FileList object is, how you get it from an input type file element, and how to read each File with index access, item() and length property.
A FileList is the object the browser gives you when the user selects one or more files. You get one from the files property of an <input type="file" /> element, and each item inside it is a File object.
That’s not the only place that can give you a FileList object. You will get one also when interacting with Drag and Drop, through the files property of the DataTransfer object.
Sticking to forms, the input type by default does not allow multiple files to be uploaded.
You will retrieve a FileList with just one element, and you can retrieve it using this syntax:
<input type="file" />
const input = document.querySelector('input')
input.addEventListener('change', (e) => {
const fileList = input.files
const theFile = fileList[0]
})
The change event fires when the user picks a file. Selecting any element from a FileList object will get a File object. In this case we just have one, so we select the item at position 0.
You can also retrieve it using the item() method, specifying the index:
const input = document.querySelector('input')
input.addEventListener('change', (e) => {
const fileList = input.files
const theFile = fileList.item(0)
})
Handling multiple files
If multiple is enabled though, using the multiple attribute (<input type="file" multiple />), FileList will contain multiple elements.
You can get the count by looking at the length property of FileList.
This example loads the files uploaded and iterates on them to print each file’s name:
<input type="file" multiple />
const input = document.querySelector('input')
input.addEventListener('change', (e) => {
const files = input.files
const filesCount = files.length
for (let i = 0; i < files.length; i++) {
const file = files[i]
alert(file.name)
}
})
Each File object gives you the file’s name, its size in bytes, its MIME type, and the lastModified timestamp. That’s usually all you need to validate an upload before sending it to the server.
It’s not an array
Here’s the thing that trips people up: a FileList looks like an array, but it isn’t one.
It has indexed access and a length property, and you can loop over it with for...of. But it has none of the array methods. This throws a TypeError:
input.files.map((file) => file.name) //TypeError: input.files.map is not a function
The fix is to convert it to a real array first:
const names = Array.from(input.files).map((file) => file.name)
Also note a FileList is read-only. You can’t add or remove files from it in JavaScript. If you want to clear the user’s selection, reset the input instead, with input.value = ''.
Related posts about platform: