[javascript] How to check file input size with jQuery?

I have a form with file upload capabilities and I would like to be able to have some nice client side error reporting if the file the user is trying to upload is too big, is there a way to check against file size with jQuery, either purely on the client or somehow posting the file back to the server to check?

This question is related to javascript jquery file-upload

The answer is


This code:

$("#yourFileInput")[0].files[0].size;

Returns the file size for an form input.

On FF 3.6 and later this code should be:

$("#yourFileInput")[0].files[0].fileSize;

I am posting my solution too, used for an ASP.NET FileUpload control. Perhaps someone will find it useful.

    $(function () {        
    $('<%= fileUploadCV.ClientID %>').change(function () {

        //because this is single file upload I use only first index
        var f = this.files[0]

        //here I CHECK if the FILE SIZE is bigger than 8 MB (numbers below are in bytes)
        if (f.size > 8388608 || f.fileSize > 8388608)
        {
           //show an alert to the user
           alert("Allowed file size exceeded. (Max. 8 MB)")

           //reset file upload control
           this.value = null;
        }
    })
});

<form id="uploadForm" class="disp-inline" role="form" action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file">
</form>
<button onclick="checkSize();"></button>
<script>
    function checkSize(){
        var size = $('#uploadForm')["0"].firstChild.files["0"].size;
        console.log(size);
    }
</script>

I found this to be the easiest if you don't plan on submitted the form through standard ajax / html5 methods, but of course it works with anything.

NOTES:

var size = $('#uploadForm')["0"]["0"].files["0"].size;

This used to work, but it doesn't in chrome anymore, i just tested the code above and it worked in both ff and chrome (lastest). The second ["0"] is now firstChild.


Use below to check file's size and clear if it's greater,

    $("input[type='file']").on("change", function () {
     if(this.files[0].size > 2000000) {
       alert("Please upload file less than 2MB. Thanks!!");
       $(this).val('');
     }
    });

If you want to use jQuery's validate you can by creating this method:

$.validator.addMethod('filesize', function(value, element, param) {
    // param = size (en bytes) 
    // element = element to validate (<input>)
    // value = value of the element (file name)
    return this.optional(element) || (element.files[0].size <= param) 
});

You would use it:

$('#formid').validate({
    rules: { inputimage: { required: true, accept: "png|jpe?g|gif", filesize: 1048576  }},
    messages: { inputimage: "File must be JPG, GIF or PNG, less than 1MB" }
});

Plese try this:

var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;

if (sizeInKB >= sizeLimit) {
    alert("Max file size 30KB");
    return false;
}

You can do this type of checking with Flash or Silverlight but not Javascript. The javascript sandbox does not allow access to the file system. The size check would need to be done server side after it has been uploaded.

If you want to go the Silverlight/Flash route, you could check that if they are not installed to default to a regular file upload handler that uses the normal controls. This way, if the do have Silverlight/Flash installed their experience will be a bit more rich.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to file-upload

bootstrap 4 file input doesn't show the file name How to post a file from a form with Axios File Upload In Angular? How to set the max size of upload file The request was rejected because no multipart boundary was found in springboot Send multipart/form-data files with angular using $http File upload from <input type="file"> How to upload files in asp.net core? REST API - file (ie images) processing - best practices Angular - POST uploaded file