Let’s start with the HTML required to upload a file:
<form> <p>[MAX FILE SIZE = 2MB]</p> <input id="file-input" type="file" /> <p id="file-result"></p> <input id="file-submit" type="submit" disabled /> </form>Code language: HTML, XML (xml)
Note the initial state of the submit button is
We’ll use an event listener that detects change on the file input. When the state of the file input changes (user has selected a file) we’ll then run our script that checks the selected file size:
First up in the event listener we’ll check that a file exists and then calculate the file size:
If you run the script you should get an alert message with the selected file size in MB.
Finally we’ll see if the file size is less than or equal to our size limit (2MB):
If the file size is larger than 2MB we keep the submit button disabled and prompt the user to select a smaller sized file. Otherwise, if the file is less than 2MB the submit button is enabled and a success message is displayed.