Skip to content

Instantly share code, notes, and snippets.

@w3collective
Created May 21, 2022 23:40
Show Gist options
  • Save w3collective/02458bebb62cf11e2dd7b42214b962a2 to your computer and use it in GitHub Desktop.
Save w3collective/02458bebb62cf11e2dd7b42214b962a2 to your computer and use it in GitHub Desktop.
Restrict file upload size using JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Restrict file upload size using JavaScript</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<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>
<script>
let fileInput = document.getElementById("file-input");
let fileResult = document.getElementById("file-result");
let fileSubmit = document.getElementById("file-submit");
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 = false;
}
}
});
</script>
</body>
</html>
@w3collective
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment