本文分享JS驗證上傳圖片的方法,供有需要的朋友參考。具體實現如下:
這段代碼封裝了一個UpLoadFileCheck類,用來校驗上傳文件的類型、大小以及圖片的寬高,可靈活配置允許的擴展名、文件大小與圖片尺寸。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js驗證圖片</title>
<script>
UpLoadFileCheck=function() {
this.AllowExt=".jpg,.gif"; // 允許上傳的文件類型,0為無限制
this.AllowImgFileSize=0; // 允許上傳文件的大小,0為無限制,單位KB
this.AllowImgWidth=0; // 允許上傳圖片的寬度,0為無限制,單位px
this.AllowImgHeight=0; // 允許上傳圖片的高度,0為無限制,單位px
this.ImgObj=new Image();
this.ImgFileSize=0; this.ImgWidth=0; this.ImgHeight=0; this.FileExt=""; this.ErrMsg=""; this.IsImg=false;
};
UpLoadFileCheck.prototype.CheckExt=function(obj) {
this.ErrMsg="";
this.ImgObj.src=obj.value;
if(obj.value=="") { this.ErrMsg="\n請選擇一個文件"; }\br /> else {
this.FileExt=obj.value.substr(obj.value.lastIndexOf(".")).toLowerCase();
if(this.AllowExt!=0 && this.AllowExt.indexOf(this.FileExt)==-1) { this.ErrMsg="\n該文件類型不允許上傳,請上傳 "+this.AllowExt+" 類型的文件"; }\br /> }
if(this.ErrMsg!="") { this.ShowMsg(this.ErrMsg,false); return false; }\br /> else return this.CheckProperty(obj);
};
UpLoadFileCheck.prototype.CheckProperty=function(obj) {
if(this.ImgObj.readyState!="complete") { sleep(1000); }
if(this.IsImg==true) {\br /> this.ImgWidth=this.ImgObj.width;
this.ImgHeight=this.ImgObj.height;
if(this.AllowImgWidth!=0 && this.AllowImgWidth<this.ImgWidth) this.ErrMsg=this.ErrMsg+"\n圖片寬度超過限制";
if(this.AllowImgHeight!=0 && this.AllowImgHeight<this.ImgHeight) this.ErrMsg=this.ErrMsg+"\n圖片高度超過限制";
}
this.ImgFileSize=Math.round(this.ImgObj.fileSize/1024*100)/100;
if(this.AllowImgFileSize!=0 && this.AllowImgFileSize<this.ImgFileSize) this.ErrMsg=this.ErrMsg+"\n文件大小超過限制";
if(this.ErrMsg!="") { this.ShowMsg(this.ErrMsg,false); return false; }\br /> else return true;
};
UpLoadFileCheck.prototype.ShowMsg=function(msg,tf) { alert(msg); };
function sleep(num) {\br /> var tempDate=new Date();
var theXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
while((new Date()-tempDate)<num) {\br /> try{ theXmlHttp.open("get", "about:blank?JK="+Math.random(), false ); theXmlHttp.send(); } catch(e){;}\br /> }
return;
}
function c(obj) {\br /> var d=new UpLoadFileCheck();
d.IsImg=true; d.AllowImgFileSize=100; d.CheckExt(obj);
}
</script>
</head>
<body>
<input name="" type="file" onchange="c(this)"/>
</body>
</html>
希望本文所述對大家的JavaScript程序設計有所幫助。