0

Add file size validation.

Can you help me to update this javascript to add a valid file size of 2MB before uploading it using JavaScript?

<!DOCTYPE html>
<html lang="id">  
<head>
<title></title>
<script>
var _validFileExtensions = ["pdf"];    
function ValidateSingleInput(oInput) {
    if (oInput.type == "file") {
        var sFileName = oInput.value;
         if (sFileName.length > 0) {
            var blnValid = false;
            for (var j = 0; j < _validFileExtensions.length; j++) {
                var sCurExtension = _validFileExtensions[j];
                if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                    blnValid = true;
                    break;
                }
            }
             
            if (!blnValid) {
                alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                oInput.value = "";
                return false;
            }
        }
    }
    return true;
}
</script>
</head>
<body>
File 1: <input type="file" name="file1" onchange="ValidateSingleInput(this);" /><br />
File 2: <input type="file" name="file2" onchange="ValidateSingleInput(this);" /><br />
File 3: <input type="file" name="file3" onchange="ValidateSingleInput(this);" /><br />
</body>
</html>

[![enter image description here][1]][1]
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
yooyo
  • 65
  • 2
  • 10
  • 1
    Does this answer your question? [JavaScript file upload size validation](https://stackoverflow.com/questions/3717793/javascript-file-upload-size-validation) – Evgenii Klepilin Jan 22 '20 at 06:56

1 Answers1

1

You can do it with the FILE API (check browser support).

files[0].size returns the size of the file in bytes.

var filesize = oInput.files[0].size
Sebastian
  • 11
  • 1