JS实现图片预览

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

    function checkType(upload){
        var image = document.getElementById(upload).value;
        var extStart = image.lastIndexOf(".");
        var ext = image.substring(extStart, image.length).toUpperCase();
        if ( ext != ".PNG" && ext != ".GIF" && ext != ".JPG" && ext != ".JPEG") {
            alert("图片限于png,gif,jpeg,jpg格式!");
            return false;
        }
        return true;
    }
    function setImagePreview(upload,preview) {
        if(checkType(upload)){
            
            var docObj=document.getElementById(upload);
            var imgObjPreview=document.getElementById(preview);
                imgObjPreview.style.display = 'block';
                imgObjPreview.style.width = '160px';
                imgObjPreview.style.height = '120px';
            if(docObj.files &&    docObj.files[0]){
                try{
                    imgObjPreview.src = docObj.files[0].getAsDataURL();
                }catch(e){
                    //火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式
                    imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
                }


            }else{
                //IE下,使用滤镜
                docObj.select();
                var imgSrc = document.selection.createRange().text;
                //图片异常的捕捉,防止用户修改后缀来伪造图片
                try{
                    imgObjPreview.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                    imgObjPreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
                }catch(e){
                    alert("您上传的图片格式不正确,请重新选择!");
                    return false;
                }
                imgObjPreview.style.display = 'none';
                document.selection.empty();
            }
            return true;
        }

    }