signed

QiShunwang

“诚信为本、客户至上”

图片上传判断及预览脚本的效果实例

2021/6/3 14:36:45   来源:
复制代码 代码如下:

<div id="imgbox">
    <img id="imghead" src="img/no_photo.gif" alt="" width="100" height="125" />
    </div>
<asp:FileUpload ID="FileUploadImg" runat="server" onchange='previewImage(this);'
                            style="position:relative;left:-130px;cursor:pointer;"/>
var $$ = function(id) {
    return "string" == typeof id ? document.getElementById(id) : id;
};
/*
图片验证
*/
//验证上传图片格式
function checkupload(ele) {
    var obj = $$("FileUploadImg");
    var fileContentType = obj.value.match(/^(.*)(\.)(.{1,8})$/)[3]; //这个文件类型正则很有用:)   
    if (fileContentType == 'gif' || fileContentType == 'jpeg' || fileContentType == 'png' || fileContentType == 'jpg') {
        //验证上传图片大小
        return checkFileSize(ele);
    } else {
        alert('上传文件格式不正确!');
        return false;
    }
    return false;
}
//验证上传图片大小
function checkFileSize(ele) {
    var maxSize = 100 * 1024;
    //ie
    if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
        var fso;
        try {
            fso = new ActiveXObject('Scripting.FileSystemObject');
            var file = fso.GetFile(ele.value);
            //alert(file.Size);
            return file.Size < maxSize;
        } catch (e) {
            alert("浏览器设置禁用ActiveXObject控件,请启用");
            return false;
        }
    }
    //firefox
    else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
        //alert(ele.files[0].fileSize);
        return ele.files[0].fileSize < maxSize;
    }
    return false;
}
//加载预览图片
function previewImage(ele) {
    if (ele && checkupload(ele)) {
        var imgDiv = $$("imgbox");
        imgDiv.innerHTML = "";
        imgDiv.style.width = "100px";
        imgDiv.style.height = "125px";
        //ie
        if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
            imgDiv.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod = scale)";
            imgDiv.filters("DXImageTransform.Microsoft.AlphaImageLoader").src = ele.value;
        }
        //firefox
        else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
            imgDiv.innerHTML = "<img width='" + 100 + "' height='" + 125 + "' id='aPic' src='" + ele.files.item(0).getAsDataURL() + "'>";
        } else {
            imgDiv.innerHTML = "<span style='color:red;'>IE/火狐浏览器才支持图片预览</span>";
        }
    } else {
        $$("FileUploadImg").value = "";
        $$("imgbox").innerHTML = "<img id='imghead' src='img/no_photo.gif' alt='' width='100' height='125' />";
        //alert('重置上传控件');
    }
}
您可能感兴趣的文章:
  • JS上传前预览图片实例
  • js实现上传图片之上传前预览图片
  • jquery 图片上传按比例预览插件集合
  • javascript实现上传图片并预览的效果实现代码
  • javascript 图片上传预览-兼容标准