You do not want to flood your server with a bunch of files that are huge in size and run out of disk space. Disk space on a server costs a lot of money and you must utilize it efficiently.
To upload a file, you only need an input element of type file. When you select a file, you will get an array of File objects and it is not hard to detect file size after that.
The only thing which you have to keep in mind is that the File object will give you file size in bytes. So whatever file size limitation you want to impose, you must do the comparison in bytes.
In the following example, we have an input field of type file and we are restricting file upload size to 10 kb. If the file size exceeds 10 kb, we will show an error. Please have a look over the code example and the steps given below.
HTML & CSS
We have 3 elements in the HTML file (div, input, and span). The div element is just a wrapper for the rest of the elements.
The input element is of type file which gives us the ability to select a file.
We have an empty span element and that will be used to display an error message if any.
We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
We have selected the input element and the span element using the document.querySelector() method and stored them in the input and span variables respectively.
We have attached a change event listener to the input element.
In the event handler function, the files property of the input element returns an array of File objects and we are storing that in the files variable.
We are making use of the if statement to verify whether the files array is empty or not. If the user has selected a file, then the length property will always return a value greater than 0.
As you know, arrays have a 0-based index. We are getting the first File object by passing an index of 0. Each File object has a size property that returns the size of the file in bytes. One kilobyte is equal to 1024 bytes.
We are comparing the file size and if it is greater than 10 kb, we are displaying an error message in the span element using the innerText property.