2017-10-18 104 views
1

在我的項目中,我使用ajaxSubmit來上傳文件。如何在上傳文件之前使用ajaxSubmit獲取文件大小

文件大小有限。所以在發送文件之前,我想立即檢查上傳文件的大小。

當我點擊文件按鈕時,alert("test")工作成功。但alert(ufile.size)工程失敗。

我試過$('#fId').files[0]$('#fulId').files[0],但它們都失敗了。

這裏是我的js代碼:

$(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(){} 
    }); 
    }); 

下面是HTML代碼:

<div class="attFile"> 
    <input type="file" id="fulId" name="mypic"> 
</div> 
+0

的可能的複製[如何檢查文件輸入大小與jQuery的?](https://stackoverflow.com/questions/1601455/how-to-check-file-input-size-with-jquery) –

回答

2

在你改變功能,使用alert(this.files[0].size);

這是jQuery的一個有趣的警告。 JQuery不會返回dom的所有屬性,就像普通的JavaScript一樣。 jQuery不會返回文件屬性。你可以使用下面的代碼來訪問你的jQuery的第一個匹配的DOM元素:

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

嘗試下面的代碼

$('#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>

相關問題