1

In my project, I use ajaxSubmit to upload file.

The file size shoulde be limited. So before sending the file, I want to check the size of uploaded file immediately.

When I click file button, alert("test") works successfully. But alert(ufile.size) works fail.

I have tried $('#fId').files[0] and $('#fulId').files[0], but they both works fail.

Here is my js code:

$(function () { 
$("#fulId").wrap("<form id='fId' action='action.php' method='post' enctype='multipart/form-data'></form>");
$("#fulId").change(function(){
    alert("test");
    $("#fId").ajaxSubmit({
        dataType:'json',
        beforeSend: function(){
         //var ufile=$('#fId').files[0];
         var ufile=$('#fulId').files[0];
         alert(ufile.size);
        },
        uploadProgress: function(){},
        success: function(){},
        error:function(){}
    });
  });

Here is html code:

<div class="attFile">
   <input type="file" id="fulId" name="mypic">
</div>
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
Snow
  • 71
  • 1
  • 11
  • Possible duplicate of [How to check file input size with jQuery?](https://stackoverflow.com/questions/1601455/how-to-check-file-input-size-with-jquery) – S. Walker Oct 18 '17 at 01:15

2 Answers2

2

In your change function, use alert(this.files[0].size);

This is an interesting caveat of jQuery. JQuery does not return all properties of the dom, like normal JavaScript does. And the file property is not returned by jQuery. You could use the following code to access the first matching dom element of your jQuery:

  $("#yourFileInput")[0].files[0].size;
S. Walker
  • 2,129
  • 12
  • 30
1

Try following code

$('#myUP').bind('change', function() {
  
  alert( "File size in bytes "+ this.files[0].size);

});
<input type="file" id="myUP" /><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Nisal Edu
  • 7,237
  • 4
  • 28
  • 34