Jenninha
Jenninha

Reputation: 1377

Sum file upload input tags size

I have more than one input type=file tags in my form. Sometimes one will be hidden and sometimes there will be multiples created dynamically. I would like that on my form submit I check the file size of each file and I would sum them and check if it exceeds the maximum I set.

I wrote the code below:

function AcceptableFileUpload() {
    var totalsize = 0;
    var fileUploads = $("#form1 input[type=file]").length;
    for (var i = 0; i < fileUploads; i++) {
        //I added this to check whether there is any file here 
        //as I was receiving undefined when my hidden input file was checked
        if ($('#form1 input[type=file]').get(i).length > 0) {
            var filesize = $('#form1 input[type=file]').get(i).files[0].size;
            totalsize = +filesize;
        }
    }
    if (totalsize > 1073741) {
        alert("File size limit exceeded");
        return false;
    }
    return true;
}

When I only used var filesize = $('#form1 input[type=file]').get(0).files[0].size; I got the file size correctly, but it didn't work the way I wrote above, it says that the size is 0 always. I'd appreciate your help, thanks!

Upvotes: 0

Views: 1406

Answers (1)

Manish
Manish

Reputation: 1447

You can try

function AcceptableFileUpload() {
   var totalsize = 0;

   $('#form1 input:file').each(function(){
     if($(this).val().length > 0){
        totalsize=totalsize+$(this)[0].files[0].size;
      }
  });
  if (totalsize > 1073741) {
      alert("File size limit exceeded");
      return false;
  }
  return true;

}

Upvotes: 2

Related Questions