您实际上不能访问文件系统(例如读写本地文件) ,但是,由于 HTML5 File Api 规范,有一些文件属性是您可以访问的,文件大小就是其中之一。
对于下面的 HTML
<input type="file" id="myFile" />
尝试以下方法:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {
//this.files[0].size gets the size of your file.
alert(this.files[0].size);
});
$.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)
});
你会用它:
$('#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" }
});
$(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;
}
})
});
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;
}