[代码片段]javascript检查图片大小和格式

时间:2023-03-09 06:46:08
[代码片段]javascript检查图片大小和格式
function checkImgType(input) {
var this_ = document.getElementsByName('imgFile')[0];
var filepath = this_.value;
var extStart = filepath.lastIndexOf(".");
var ext = filepath.substring(extStart, filepath.length).toUpperCase();
if (ext != ".PNG" && ext != ".GIF" && ext != ".JPG") {
alert("图片限于png,gif,jpg格式");
return false;
}
var file_size = 0;
if ($.browser.msie) {
var img = new Image();
img.src = filepath;
if (img.fileSize > 0) {
if (img.fileSize > 2 * 1024*1024) {
alert("图片不大于2MB。");
document.execCommand("delete");
return false;
}
}
} else {
file_size = this_.files[0].size;
console.log(file_size / 1024 / 1024 + " MB");
var size = file_size / 1024 / 1024;
//alert(size);
if (size > 2) {
alert("上传的文件大小不能超过2M!");
return false;
}
}
return true;
}