Learn about the File object and how to utilize it

Browsers provide us with a File object. The File object is a Blob object and has 3 properties:

  • name (a String)
  • lastModified (the UNIX timestamp of the last modified date time)

These properties are in addition to the Blob object properties:

  • size (the size in bytes)
  • type (the MIME type)

You will receive a File object when interacting with the FileList object, which can be obtained from an HTML form using an <input type="file" /> element or when working with Drag and Drop.

When you have a FileList object, you can loop over it or select an element (e.g., the first item with myFileList[0]) to retrieve a File object.

Suppose you have an <input type="file"> element in your form:

<input type="file" />

You can listen for the change event on this element to get information about the selected file. document.querySelector('input').files will return a FileList object, as mentioned above. Using [0], you can access the first loaded file and all the necessary properties from the File object:

document.querySelector('input').addEventListener('change', () => {
  const file = document.querySelector('input').files[0];
  alert(`The file ${file.name} was last modified on ${new Date(file.lastModified).toDateString()}`);
});

See the Pen File object demo by Flavio Copes on CodePen.