Sometimes, we want to get the selected file’s size in JavaScript.
In this article, we’ll look at how to get the selected file’s size in JavaScript.
Get the Selected File’s Size in JavaScript
To get the selected file’s size in JavaScript, we can use the size property of the file object to get the file’s size in bytes.
For instance, we write:
<input type='file'>
to add a file input.
Then, we write:
const fileInput = document.querySelector("input");
fileInput.addEventListener('change', (e) => {
const [file] = e.target.files
console.log(file.size)
})
to select the file input with document.querySelector.
Then we call addEventListener with 'change' to listen for file selection.
In the event handler callback, we get the file from e.target.files with destructuring.
Then we get size of the file in bytes with the size property.
Now we should see the selected file’s size logged whenever we select a file.
Conclusion
To get the selected file’s size in JavaScript, we can use the size property of the file object to get the file’s size in bytes.