Course contentsShow
← JavaScript
Lesson 2368 of 2,72348. Working with Binary DataFree lesson

Getting Files from Input Elements

Access File objects from file input elements using the files property and FileList interface.

Getting Files from Input Elements

What you'll learn: How to access user-selected files from <input type="file"> elements using JavaScript.

Why This Matters

When users select files through a file input in your web page, those files don't automatically upload or become available to your code. You need to explicitly retrieve them using the input element's files property, which gives you a special FileList containing File objects you can then read or process.

The Files Property and FileList

Every <input type="file"> element has a files property. When a user selects one or more files (depending on whether the multiple attribute is present), this property holds a FileList — an array-like collection of File objects.

Think of FileList as a read-only snapshot of the files the user chose. It looks like an array (you can access items by index and it has a length property), but it's actually a specialized object.

Accessing the Files

const inputElement = document.querySelector('input[type="file"]');

inputElement.addEventListener('change', (event) => {
  const fileList = event.target.files;
  
  console.log(`User selected ${fileList.length} file(s)`);
  
  // Access the first file
  const firstFile = fileList[0];
  
  if (firstFile) {
    console.log('Name:', firstFile.name);
    console.log('Size:', firstFile.size);
    console.log('Type:', firstFile.type);
  }
});

For multiple files, you can iterate using a for loop or convert FileList to an array with Array.from(fileList).

The most common pattern is listening for the change event, then accessing event.target.files to retrieve the FileList containing all selected File objects.

Key Takeaway: Use the files property on file input elements to access a FileList of user-selected File objects, typically within a change event listener.