1. 参考文章:jQuery 判断文件上传类型,我稍微修改了一下,用来做图片的上传判断。
代码如下:
<span style="font-size:14px;"><span style="white-space:pre"> </span><span style="font-family:Arial;">$("#picture").live('change',function(){
var rightFileType = new Array('jpg', 'bmp', 'gif', 'png', 'jpeg');
var fileType = $(this).val().substring($(this).val().lastIndexOf('.') + 1);
if (!PROJECT.inArray(fileType.toLowerCase(), rightFileType)) {
this.outerHTML += '';
this.value ="";
alert("只支持图片文件上传!");
}
alert(1)
var file_size = 0;
if ( $.browser.msie && !this.files ) {
var file_path = this.value;
var file_system = new ActiveXObject("Scripting.FileSystemObject");
var file = file_system.GetFile (file_path);
file_size = file.Size;
alert(file_size/1024/1024 + " MB");
} else {
file_size = this.files[0].size;
console.log(file_size/1024/1024 + " MB");
}
var size = file_size / 1024;
if(size > 300){
alert("上传的文件大小不能超过10M!");
}
});
},
inArray: function(needle, haystack) {
var type = typeof needle;
if(type == 'string' || type =='number') {
for(var i in haystack) {
if(haystack[i] == needle) {
return true;
}
}
}
return false;
},</span></span>
2. html
<span style="font-family:Arial;font-size:14px;"><span style="white-space:pre"> </span><div class="controls">
<input id="picture" type="file" size="45" name="picture" class="input">
<button class="btn btn-default" type="button" onclick="PROJECT.checkPictureExtension()">Upload</button>
<p class="help-block"></p>
</div></span>
3. 判断图片的类型和大小最后的定型:
$("#picture").live('change',function(){
var rightFileType = new Array('jpg', 'bmp', 'gif', 'png', 'jpeg');
var fileType = $(this).val().substring($(this).val().lastIndexOf('.') + 1);
var file_size = this.files[0].size;
alert(this.files[0].size + '--' + this.files[0].type + '--' + this.files[0].name + '--');
if (!PROJECT.inArray(fileType.toLowerCase(), rightFileType)) {
this.outerHTML += '';
this.value ="";
$('.help-block').css('color', 'red').html("只支持图片文件上传!");
} else {
var size = file_size / 1024;
if(size > 300){
this.outerHTML += '';
this.value ="";
$('.help-block').css('color', 'red').html("上传的文件大小不能超过10M!");
} else {
$('.help-block').html('');
}
}
});
},
inArray: function(needle, haystack) {
var type = typeof needle;
if(type == 'string' || type =='number') {
for(var i in haystack) {
if(haystack[i] == needle) {
return true;
}
}
}
return false;
},
<div class="controls">
<input id="picture" type="file" size="45" name="picture" class="input">
<button class="btn btn-default" type="button" onclick="PROJECT.uploadPicture(this)">Upload</button>
<p class="help-block"></p>
</div>