/

The FileList Object: An Overview and Usage Guide

The FileList Object: An Overview and Usage Guide

Learn about the FileList object and how to effectively utilize it for file uploads.

When working with an HTML form that includes an <input type="file" /> element, you will interact with a FileList object when the user uploads one or more files. However, it’s worth noting that the FileList object is not limited to form submissions only. It is also generated when using drag and drop functionality.

By default, when using the file input type, the user can only select and upload a single file. In this case, you can access the FileList object with the following code snippet:

1
<input type="file" />
1
2
3
4
5
6
const input = document.querySelector('input');

input.addEventListener('change', e => {
const fileList = input.files;
const theFile = fileList[0];
});

Here, we retrieve the FileList object and select the file at position 0, as there is only one file being uploaded.

Alternatively, you can retrieve the file using the item() method and specifying the index:

1
2
3
4
5
6
const input = document.querySelector('input');

input.addEventListener('change', e => {
const fileList = input.files;
const theFile = fileList.item(0);
});

When the file input type allows multiple files to be uploaded (by including the multiple attribute, <input type="file" multiple />), the FileList object will contain multiple files. You can determine the number of files by accessing the length property of the FileList object.

The following example demonstrates how you can load and iterate through the uploaded files to display each file’s name:

1
<input type="file" multiple />
1
2
3
4
5
6
7
8
9
10
11
const input = document.querySelector('input');

input.addEventListener('change', e => {
const files = input.files;
const filesCount = fileList.length;

for (let i = 0; i < files.length; i++) {
const file = files[i];
alert(file.name);
}
});

In this case, we retrieve the FileList object and iterate over each file, displaying the file name using the name property.

Tags: FileList object, file uploads, forms, drag and drop, multiple files, HTML form.