Get file input size using JQuery.

In this guide, I will be showing you how to get the size of a selected input file using JQuery. For the purposes of this example, I am going to assume that you want to get the size of an image before the user uploads it. That way, you can avoid any unnecessary file transfers between the browser and your server.

Caution.

Firstly, it is worth noting that you should never rely on client-side validation. A malicious user can easily side-step these kind of file size checks if you have no server-side validation in place. This should only be used for the sake of providing a more user-friendly upload form.

Our input file field.

Let’s assume that we have a simple input file field like so:

As you can see, I have given this field the ID “image“.

Now imagine that we have a JavaScript function called upload, which is called whenever the user attempts to the submit the form and upload the file.

Here is an example of this function in action:

In the JavaScript function above:

  • We set the max file size to 2MB. You can obviously change this to suit your own needs.
  • We retrieved the selected file element from our input field using JQuery’s selector.
  • Using the size attribute, we retrieved the size of the file in bytes.
  • Afterwards, we converted these bytes into MB by using theĀ Math.pow function.
  • Finally, if the size of the file is too large, we display an error message to the user and return a boolean FALSE value so that the form is not submitted to the server. Note that we used the toFixed() function round the file size in MB to two decimal places.

Older browsers.

Unfortunately, this check will not work in older browsers such as Internet Explorer 8. Fortunately, it is 2019 and worrying about old IE browsers is not as much as a problem as it used to be. Still, this is something that you should be weary about if you intend on supporting a large userbase. As stated above – you should not be relying on this to validate the form data. This should be seen as more of a UX improvement.

Facebook Comments