/** * 上传图片检测 * @param allowImgFileSize 允许的图片文件大小(kb) * @param allowImgExt 允许的图片格式("." + ext + "|") * @constructor */ function UploadImgCheck(allowImgFileSize, allowImgExt) { //私有变量和私有函数 var imgObj = new Image(), allImgExt = ".jpg|.jpeg|.gif|.bmp|.png|", //全部图片格式 fileObj, imgFileSize, imgWidth, imgHeight, fileExt, errMsg, fileMsg, hasCheked, isImg = false; //图片相关属性 allowImgFileSize = allowImgFileSize || 100; imgObj.onerror = function () { errMsg = '\n图片加载出错!'; }; //检测图片属性 function checkImgProper(obj) { fileObj = obj; try { //for FF,Chrome imgFileSize = Math.round(fileObj.files[0].size / 1024); } catch (ex) { //for MSIE var fileSystem = new ActiveXObject("Scripting.FileSystemObject"); var file = fileSystem.GetFile(fileObj.value); imgFileSize = Math.round(file.Size / 1024); } if (allowImgFileSize !== "0" && imgFileSize > allowImgFileSize) { errMsg = "图片文件大小超过限制。请上传小于" + allowImgFileSize + "KB的图片"; showcheckdMsg(errMsg); obj.value = ""; } } //显示信息 function showcheckdMsg(msg) { //TODO alert(msg); } //预览图片 function preshowImg(str) { //TODO } //特权方法(公有方法) //检测图片类型 this.checkImgExt = function (obj) { fileExt = obj.value.substring(obj.value.lastIndexOf(".") + 1); //检测格式是否与配置的匹配 if (allImgExt.indexOf(fileExt + "|") !== -1) { isImg = true; imgObj.src = obj.value; checkImgProper(obj); } else { errMsg = "该文件类型不允许上传。请上传 " + allowImgExt + " 类型的文件,当前文件类型为" + fileExt; showcheckdMsg(errMsg); obj.value = ""; } }; // if (typeof allowImgFileSize === "undefined") { allowImgFileSize = fileSize; } if (typeof allowImgExt === "undefined") { allowImgExt = allImgExt; } } var imgcheck = new UploadImgCheck(20, ".jpg|.jpeg|.gif|.png|"); document.getElementById("picuploader").onchange = function () { imgcheck.checkImgExt(this); }