Validation of file size while uploading using JavaScript

We can implement file size validation by checking file size before uploading using Javascript. For eg: If we don’t allow uploading a file more than 4MB or less than 2MB, we could use validation to check that the file the user has chosen follows the given requirements and if it doesn’t, give them a message.

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, Megabytes in this case by Math.round((filesize/1024)).
  • Check if the size follows your desired criteria.

Approach 2: 

  • 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.
Approach1:  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';
                    }
                }
            }
        }
Approach2:  $('#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>');
            }
        });

Leave a comment

Your email address will not be published. Required fields are marked *