The File Object
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:
name(a String)lastModified(the UNIX timestamp of the last modified date time)
which adds up 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 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/
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.