Native Javascript approach:
<!DOCTYPE html> <html> <head> <title>File Validation-1</title> </head> <body> <p> <input type="file" id="file" onchange="Filevalidation()" /> </p> <p id="size"></p> </body> <script> Filevalidation = () => { const fi = document.getElementById('file'); // Check if any file is selected. if (fi.files.length > 0) { for (const i = 0; i <= fi.files.length - 1; i++) { const fsize = fi.files.item(i).size; const file = Math.round((fsize / 1024)); // The size of the file. if (file >= 4096) { alert("File too Big, please select a file less than 4mb"); } else if (file < 2048) { alert("File too small, please select a file greater than 2mb"); } else { document.getElementById('size').innerHTML = '<b>' + file + '</b> KB'; } } } } </script> </html>
jQuery approach:
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>JQuery File Validation</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body> <input id="file" type="file" name="file" /> <p id="output"></p> <script type="text/javascript"> $('#file').on('change', function() { const size = (this.files[0].size / 1024 / 1024).toFixed(2); if (size > 4 || size < 2) { alert("File must be between the size of 2-4 MB"); } else { $("#output").html('<b>' + 'This file size is: ' + size + " MB" + '</b>'); } }); </script> </body> </html>
Source:
https://www.geeksforgeeks.org/validation-of-file-size-while-uploading-using-javascript-jquery/