Skip to content

The File Object

New Course Coming Soon:

Get Really Good at Git

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

Browsers provide us a File object.

The File object is a Blob object, and it provides 3 properties on top of it:

which adds up to the Blob object properties:

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

When you got a FileList object, when you loop over it or you pick an element (for example the first item with myFileList[0]) you will get a File object.

Say you have an input type="file" element in your form:

<input type="file" />

Now you can listen for the change event on this element, so when you choose a file you’ll get information about it. document.querySelector('input').files will return a FileList object, like explained above, and using [0] we get the first file loaded, and we can access all the properties we need 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 it on codepen: https://codepen.io/flaviocopes/pen/EzxdMm/

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: