#AD Top Online Web Development & Programming Courses | Udemy

Restrict file upload size using JavaScript

Last modified May 22nd 2022 | #js | GitHub Source Code [GitHub]

In this tutorial we’ll be using JavaScript to restrict the size of a file upload. When building websites that allow users to upload files this helps manage the amount of disk space required. This script will work with any file type as we are simply using the HTML file input.

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 disabled. This will prevent the form from submitting (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 inside the event listener we 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 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):

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.

Related Posts

#AD Shop Web Developer T-Shirts