In this tutorial we’ll be using JavaScript to restrict the size of a file upload. When developing websites that allow users to upload files restricting the size helps manage the amount of disk space required along with preventing errors if an upload fills the available disk space. This script will work with any type of file supported by the HTML file input element.
Let’s start with the HTML required for a file upload:
<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 that the initial state of the submit button is disabled
. This will prevent the form from be submitted (assuming the user has JavaScript enabled) until we have checked the file size.
Now for the JavaScript, first some variables that reference the HTML elements:
let fileInput = document.getElementById("file-input");
let fileResult = document.getElementById("file-result");
let fileSubmit = document.getElementById("file-submit");
Code language: JavaScript (javascript)
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:
fileInput.addEventListener("change", function () {
// TODO
});
Code language: JavaScript (javascript)
First up in the event listener we’ll check that a file exists and then calculate the file size:
fileInput.addEventListener("change", function () {
if (fileInput.files.length > 0) {
const fileSize = fileInput.files.item(0).size;
const fileMb = fileSize / 1024 ** 2;
alert(fileMb);
}
});
Code language: JavaScript (javascript)
If you run this script you should get an alert message with the size of the file uploaded in MB.
Finally we’ll see if the file size is less than or equal to our size limit (2MB):
fileInput.addEventListener("change", function () {
if (fileInput.files.length > 0) {
const fileSize = fileInput.files.item(0).size;
const fileMb = fileSize / 1024 ** 2;
if (fileMb >= 2) {
fileResult.innerHTML = "Please select a file less than 2MB.";
fileSubmit.disabled = true;
} else {
fileResult.innerHTML = "Success, your file is " + fileMb.toFixed(1) + "MB.";
fileSubmit.disabled = true;
}
}
});
Code language: JavaScript (javascript)
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.
That’s all for this tutorial, using what you’ve learned you should now be able restrict the size of a file upload using JavaScript. While you’re here be sure to checkout our ever growing collection of JavaScript tutorials.