How to check file size before upload in javascript
In this article, we will explain to you how to check file size before upload in Javascript. when we need to client-side validation, at that time we are using such an example.
Now, we get the file size on the change event using the Upload function, and after we will check the file size if the file size is greater than 2MB then it will return the error messages otherwise return the success message.
So you can see below our example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <!DOCTYPE html> <html lang="en"> <head> <title>How to check file size before upload in Javascript - XpetPhp</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript"> function Upload() { var image = document.getElementById("image"); if (typeof (image.files) != "undefined") { var size = parseFloat(image.files[0].size / (1024 * 1024)).toFixed(2); if(size > 2) { alert('Please select image size less than 2 MB'); }else{ alert('success'); } } else { alert("This browser does not support HTML5."); } } </script> </head> <body> <form method="post" name="frmAdd" id="frmAdd"> <label for="image">Image:</label> <input type="file" name="image" class="form-control" id="image" value="" onchange="Upload()"><br/> <button type="submit" class="btn btn-default">Submit</button> </form> </body> </html> |
Please follow and like us: