How to get image size of a form field (formData) in Javascript

Tags: , , , ,

Any idea how to get size in bytes of an image within a validating javascript function so that user will be prompted to pick a valid image size. I have seen other answers which handle this out of the form logic, but I want to know if I can get the size within the validation javascript function. Thanks

Here is my Form related code:

<form action="index.php" method="post" enctype="multipart/form-data" onsubmit="return validateForm(this)">
        function validateForm(form) {
            var image_name = form.image.value;
            if (image_name == null || image_name == "") {
                alert('Select an image');
                return false;
            } else return true;
    <label> Image (300 KB max.) <input type="file" name="image" /> </label>
    <input type="submit" value="Submit" name="submit" />


  if(isset($_POST['submit'])) {
    echo 'Entered First Name = '.$first_name;

 <form method="post" enctype="multipart/form-data" action="">
     <label for="fname"> First Name: </label> <input  type="text" name="fname"  /> <br /><br />
     <label for="file"> Select File: </label> <input  type="file" id="file" />
     <input type="submit" name="submit" value="Submit" />

 document.forms[0].addEventListener('submit', function( evt ) {
     var file = document.getElementById('file').files[0];

     if(file && file.size < 18000) { 
         //Submit form
        alert('Size is valid');
     } else {
        alert('pic too big');
 }, false);

Source: stackoverflow