0

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!

4
  • which browser are you using ? safari browser will show size zero on multiple file upload !. Commented Oct 18, 2013 at 10:00
  • I am testing on Firefox(24.0) and Chrome (30.0.1599.69) Commented Oct 18, 2013 at 10:01
  • if possible create one fiddle with your workaround. Commented Oct 18, 2013 at 10:03
  • Sorry, to clarify, my file uploads are not "multiple", I may have more than one input type="file" tags. Each one will only have one file. Commented Oct 18, 2013 at 10:11

1 Answer 1

2

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;

}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.