Search code examples
javascriptvalidationfile-uploadmultipartform-dataform-data

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


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)">
    <script>
        function validateForm(form) {
            var image_name = form.image.value;
            if (image_name == null || image_name == "") {
                alert('Select an image');
                return false;
            } else return true;
        }
    </script>
    <label> Image (300 KB max.) <input type="file" name="image" /> </label>
    <input type="submit" value="Submit" name="submit" />
</form>

Solution

  •  <?php
      if(isset($_POST['submit'])) {
         $first_name=$_POST['fname'];
        echo 'Entered First Name = '.$first_name;
     }
     ?>
     <html>
    
     <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" />
     </form>
    
     <script>
     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');
            evt.preventDefault();
         }
     }, false);
     </script>
     </html>