Categories
JavaScript Answers

How to Check the Size of a Selected File with JavaScript?

Spread the love

Sometimes, we may want to check the size of a selected file with JavaScript.

In this article, we’ll look at how to check the size of a selected file with JavaScript.

Using the FileReader API

Almost all modern browsers should support the FileReader API.

For instance, we can use it by writing the following HTML:

<form action='#'>
  <input type='file' id='fileinput'>
  <input type='button' id='btnLoad' value='Load'>
</form>

Then we can write the following JavaScript code:

const addPara = (text) => {
  const p = document.createElement("p");
  p.textContent = text;
  document.body.appendChild(p);
}

document
  .getElementById("btnLoad")
  .addEventListener("click", () => {
    const input = document.getElementById('fileinput');
    if (!input.files[0]) {
      addPara("Please select a file before clicking 'Load'");
    } else {
      const file = input.files[0];
      addPara(`File ${file.name} is ${file.size} bytes in size`);
    }
  });

In the HTML code, we have a form with a input with type file .

And we have a button that lets us show the file info when we click it.

In the JavaScript code, we have the addPara function that creates a p element and set the text as its content.

Then we call getElementById to get the button input element.

Then we call addEventListener to add a click listener.

In the click listener, we get the file input with getElementById .

Then we check if input.files[0] exists.

input.files[0] has the first file selected.

If there’s no file, we call addPara to show a message.

Otherwise, we call addPara to show the file info.

file.name has the filename of the selected file.

file.size has the size of the selected file in bytes.

When we select a file and click Load, we should see the file info of the selected file.

Conclusion

We can check the info of the selected file easily with the FileReader API.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *