The File Object
By Flavio Copes
Learn what the browser File object is, a Blob with name, lastModified, size and type properties, and how to read it from an input type file change event.
The File object represents a file in the browser. You get one when the user picks a file through an <input type="file"> element, or drops a file onto your page.
The File object is a Blob object, and it provides 2 properties on top of it:
name(a String)lastModified(the UNIX timestamp of the last modified date time, in milliseconds)
which add up to the Blob object properties:
size(the size in bytes)type(the MIME type)
How do you get a File object?
Say you have a file input in your form:
<input type="file" />
Listen for the change event on it. When the user picks a file, document.querySelector('input').files returns a FileList object. Pick an item from it, for example the first one with [0], and you have a File:
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()}`,
)
})
Notice that lastModified is in milliseconds, so you can pass it straight to new Date().
See it on codepen: https://codepen.io/flaviocopes/pen/EzxdMm/
If you add the multiple attribute to the input, the user can pick more than one file. Loop over the FileList to get each one:
for (const file of document.querySelector('input').files) {
console.log(file.name)
}
How do you read the file content?
Since File is a Blob, you get all the Blob reading methods for free. The text() method returns a promise that resolves with the content as a string:
const file = document.querySelector('input').files[0]
const content = await file.text()
For binary data, use arrayBuffer() the same way.
Creating a File object yourself
You can also build a File from scratch, passing the content, the name, and an options object:
const notes = new File(['Buy milk'], 'notes.txt', { type: 'text/plain' })
notes.size //8
notes.type //'text/plain'
This is handy in tests, or when you generate content in the browser and want to upload it with FormData like a regular file.
Don’t trust the type property
The browser guesses type from the file extension, not from the actual content. Rename a .zip file to photo.jpg and the browser reports image/jpeg. Files with unknown extensions get an empty string.
So checking file.type is fine for improving the UI, but it’s not validation. If your app cares about what’s inside the file, verify it on the server after the upload.
Related posts about platform: