Created
May 21, 2022 23:40
-
-
Save w3collective/02458bebb62cf11e2dd7b42214b962a2 to your computer and use it in GitHub Desktop.
Restrict file upload size using JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source => https://w3collective.com/restrict-file-size-javascript/