Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

w3collective commented May 21, 2022

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