Skip to content

The FileList Object

New Course Coming Soon:

Get Really Good at Git

Find out what is a FileList object and how to use it

When you have an HTML Form with an <input type="file" /> element, when one or more files are uploaded by the user you will interact with a FileList 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.

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]
})

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)
})

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 = fileList.length

  for (let i = 0; i < files.length; i++) {
    const file = files[i]
    alert(file.name)
  }
})
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Read my DOM Tutorial on The Valley of Code
→ Read my Browser Events Tutorial on The Valley of Code
→ Read my Browser APIs Tutorials on The Valley of Code

Here is how can I help you: