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:

<input type="file" />
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:

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:

<input type="file" multiple />
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.