Note:
1、每一个验证可以单独拆开去。只需要花费一点点功夫处理传参,返回
2、verificationPicType类型验证函数 和 verificationPicSpace大小验证函数是实时的。直接可以用函数的返回值做判断,处理之后业务逻辑。
3、但是verificationPicSize尺寸验证函数的返回不能直接用。因为内部图片加载是异步的,函数的返回值不是基于图片尺寸大小判断的结果。只能利用错误提示。根本原因是内部使用FileReader对象。
FileReader
对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用File
或Blob
对象指定要读取的文件或数据。参考连接:FileReader
好了,直接上代码
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<input type="file" name="files" id="file" onchange="verifyImageInfo(this,['jpg','png'],100,{'width':1280,'height':710})">
</body>
<script type="text/javascript">
//图片验证(大小,尺寸,类型)
function verifyImageInfo(that,allow_type_arr,allow_space,allow_size_obj){
if(verificationPicType(that,allow_type_arr)
&& verificationPicSpace(that,allow_space)){
//尺寸验证不能在判断条件。
//因为内部图片加载是异步的,函数的返回值不是基于图片尺寸大小判断的结果。只能利用错误提示
verificationPicSize(that,allow_size_obj);
return true;
}
return false;
}
/**
* 图片类型验证
* @allow_type_arr ['jpg','png'],如果数组为空则表示不限
*/
function verificationPicType(that,allow_type_arr) {
if(allow_type_arr.length==0) return true;
var fileTypes = allow_type_arr;
var filePath = that.value;
//当括号里面的值为0、空字符、false 、null 、undefined的时候就相当于false
if(filePath){
var isNext = false;
var fileEnd = filePath.substring(filePath.indexOf(".")+1).toLowerCase();
// console.log(fileEnd);
for (var i = 0; i < fileTypes.length; i++) {
if (fileTypes[i] == fileEnd) {
isNext = true;
break;
}
}
if (!isNext){
alert('不接受此文件类型');
that.value = "";
return false;
}
return true;
}else {
return false;
}
}
/**
* 图片大小验证
* @allow_space 400,如果值为0则表示不限
*/
function verificationPicSpace(that,allow_space) {
if(allow_space==0) return true;
var fileSize = 0;
var fileMaxSize = allow_space;
var filePath = that.value;
if(filePath){
fileSize =that.files[0].size;
var size = fileSize / 1024;//单位b转换kb
// console.log(size);
if (size > fileMaxSize) {
alert("文件大小超出限制!");
that.value = "";
return false;
}else if (size <= 0) {
alert("文件大小不能为0!");
that.value = "";
return false;
}
return true;
}else{
return false;
}
}
/**
* 图片尺寸验证
* @allow_size_obj {'width':123,"height":345},如果值为0则表示不限
*/
function verificationPicSize(that,allow_size_obj) {
var filePath = that.value;
if(filePath){
//读取图片数据
var filePic = that.files[0];
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
//加载图片获取图片真实宽度和高度
var image = new Image();
image.onload=function(){
var width = image.width;
var height = image.height;
if(width!=allow_size_obj['width'] && allow_size_obj['width']!=0){
alert("文件宽度"+width+"不符合要求");
that.value = "";
return false;
}
if(height!=allow_size_obj['height'] && allow_size_obj['height']!=0){
alert("文件高度"+height+"不符合要求");
that.value = "";
return false;
}
return true;
};
image.src= data;
};
reader.readAsDataURL(filePic);
}else{
return false;
}
}
</script>
</html>
吃水不忘挖井人