简体   繁体   中英

How to check maximum upload file size in javascript validation?

i have a code but i need a javascript validation that check maximum upload file size like check if uploaded file is increased 1-MB he show error file is increased chosse less then 1MB file ...

i have this code how use maximum file size regular expression and whar code i use in this code that check maximum size validation.

<form action="" method="post">
 <script type="text/javascript">
   function ValidateExtension() {
     var allowedFiles = [".doc", ".docx", ".pdf"];
     var fileUpload = document.getElementById("fileUpload");
     var lblError = document.getElementById("lblError");
     var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
     if (!regex.test(fileUpload.value.toLowerCase())) {
       lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
       return false;
     }
     lblError.innerHTML = "";
     return true;
   }
 </script>
<input id="fileUpload" type="file" /> 
<br /> 
<span id="lblError" style="color: red;"></span> 
<br /> 
<input type="submit" id="btnUpload" value="Upload" onclick="return ValidateExtension()" /> 
</form>

This should get you started.

 function validate(el) { var maxfilesize = 1024 * 1024, // 1 Mb filesize = el.files[0].size, warningel = document.getElementById( 'lbError' ); if ( filesize > maxfilesize ) { warningel.innerHTML = "File too large: " + filesize + ". Maximum size: " + maxfilesize; return false; } else { warningel.innerHTML = ''; return true; } } 
 .warning { font-style: italic; } 
 <form enctype="multipart/form-data" method="POST"> <input type='file' name='f' onchange='validate(this)'> <div id='lbError' class='warning'></div> <input type='submit' onsubmit='return validate()'/> </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM