jQuery input file size and type

Photo by Edu Lauton on Unsplash

jQuery input file size and type

jQuery Jan 2, 2023

In this article, we will develop the example by adding file size and extension checks before uploading.

Checking file extension and size

When creating interactive sites, it is necessary to take into account that it is necessary to point out errors in detail. For example, a user might try to upload a PDF document to a form that only accepts JPG images. Or try to send a file that is too large to the site.

To prevent such misunderstandings, it is necessary to check the file extension and their size before starting the AJAX download. Let's try to write the verification code for this. Let's say we have the form from the previous example:

<input type="file" name="photo">

It is necessary to check the type and size of the file immediately after selecting it in the file window. This is done using js / jq script:

$('input[name=photo]')[0].bind('change', function() {
   var size = this.files[0].size; // size in bytes
   var name = this.files[0].name; // File name

   if(5000000 < size){
      // file larger than 5 megabytes

   var fileExtension = ['jpg', 'jpeg', 'png']; // valid file types
   if ($.inArray(name.split('.').pop().toLowerCase(), fileExtension) == -1) {
      // the file has the wrong type (extension)

   // After passing all the checks
   // you can send a file via AJAX to the site.
   // But if the checks are not passed, then it is necessary
   // to show error messages to the user

This code serves to check the size and type of the file. Validation occurs immediately after selecting a file in the device explorer and before submitting the form.

Users will appreciate the interactive prompt as they fill out the form. They don't have to wait for the file to finish uploading to the site before learning that the extension doesn't fit. Of course, this validation at the client JavaScript level does not override the validation at the server script level. It is needed only for the sake of user comfort and will in no way protect the site from downloading a malicious file.


Anurag Deep

Logical by Mind, Creative by Heart