Validation of file size while uploading using JavaScript / jQuery

In this article, we will learn how to implement file size validation by checking file size before upload using Javascript and jQuery. This is a demonstration of client-side validation and is implemented to provide a nice user experience. In some cases, client-side validation is a much better method in comparison to the server-side method as it consumes less time.
For instance, if we don’t allow uploading a file more than 4MB or less than 2MB, we could use client-side validation to check that the file the user has chosen follows the given requirements and if it doesn’t, give them a message so they don’t spend all the time uploading the file only to get an error thrown away by the server.

Approach-1:

  • Listen for the change event on the input.
  • Check if any file is selected files.length > 0.
  • Get the size of the file by files.item(i).size.
  • The value will be in bytes. Convert it into any unit as you desire, Megbaytes in this case by Math.round((filesize/1024)).
  • Check if the size follows your desired criteria.

Example-1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


Output:

Before uploading a file:

If the file is greater than 4MB:

If the file is less than 2MB:

On successful upload:

Approach-2:

In the below example, we will learn how to do the same using jQuery.

  • Listen for the change event on the input.
  • Get the size of the file by this.files[0].size.
  • You can round off the obtained value as well by toFixed() method.
  • Check if the size follows your desired criteria.

Example-2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE HTML>
<html>
  
<head>
    <meta http-equiv="Content-Type" 
          content="text/html; charset=iso-8859-1" />
    <title>JQuery File Validation</title>
    <script src=
  </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>

chevron_right


Output:
Before uploading a file:

If the file is less than 2MB or greater than 4MB:

On successful upload:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.