How to limit the size of a file upload HTML input element with JavaScript?

Spread the love

Sometimes, we want to limit the size of a file upload HTML input element with JavaScript.

In this article, we’ll look at how to limit the size of a file upload HTML input element with JavaScript.

How to limit the size of a file upload HTML input element with JavaScript?

To limit the size of a file upload HTML input element with JavaScript, we listen to the change event.

For instance, we write

const uploadField = document.getElementById("file");

uploadField.onchange = (e) => {
  if (e.target.files[0].size > 10000) {
    alert("File is too big");
    e.target.value = "";
  }
};

to select the file input with getElementById.

Then we set its onchange property to a function that gets the size of the selected file in bytes with e.target.files[0].size.

We check if it’s bigger than 10000 bytes.

If it is, thenm we show an alert and empty the input.

Conclusion

To limit the size of a file upload HTML input element with JavaScript, we listen to the change event.

Leave a Reply

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