How to check file size using html5 and JavaScript?

Estimated read time 1 min read

You can check the file size of an uploaded file in JavaScript using the File object, which is part of the HTML5 File API. Here’s an example:

document.getElementById("file").addEventListener("change", function() {
  let file = this.files[0];
  let size = file.size / 1024 / 1024;
  console.log(size + " MB");
});

In this example, we use an event listener to listen for a change in the file input field. When a file is selected, we get the first file from the files array and access its size property, which returns the size of the file in bytes.

We then divide the size by 1024 to get the size in kilobytes, and divide it again by 1024 to get the size in megabytes. Finally, we log the size to the console.

Note that this approach assumes that you want to check the size of the file in megabytes. You can adjust the calculation as necessary to get the size in a different unit of measurement.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply