当前位置 : 主页 > 网络编程 > JavaScript >

图片上传时实现在本地预览

来源:互联网 收集:自由互联 发布时间:2021-07-03
图片上传时实现在本地预览 1. [代码] [JavaScript]代码 !DOCTYPE htmlhtml lang="en"head meta http-equiv="Content-Type" content="text/html; charset=utf-8" / titleBy:DragonDean/title style .file{ height: 103px; width: 103px; pos
图片上传时实现在本地预览

1. [代码][JavaScript]代码    

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>By:DragonDean</title>
    <style>
    .file{
    height: 103px;
    width: 103px;
    position: relative;
    display: inline-block;
    overflow: hidden;
  /*//  color: red;*/
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
        border:none;

    }
    .file input{
    height: 110px;
    width: 110px;
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
    z-index: 999;
    }

    .file img{
    position: absolute;
    /*border-radius: 100%;*/
    height: 100px;
    left: 1px;
    width: 100px;
    right: 0;
    top: 0;
        border: none;
    }
    </style>
    <script type="text/javascript">
        //下面用于图片上传预览功能
        function setImagePreview(avalue) {
            var docObj=document.getElementById("upload");

            var imgObjPreview=document.getElementById("pic");
            if(docObj.files &&docObj.files[0])
            {
//火狐下,直接设img属性
                console.log(docObj.files[0]);
                console.log(docObj.value);
                imgObjPreview.style.display = 'block';
//imgObjPreview.src = docObj.files[0].getAsDataURL();

//火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式
                console.log("not IE");
                console.log(window.URL.createObjectURL(docObj.value));
                console.log(window.URL.createObjectURL(docObj.files[0]));
                imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
            }
            else
            {
//IE下,使用滤镜
                console.log("IE");
                docObj.select();
                var imgSrc = document.selection.createRange().text;
                var localImagId = document.getElementById("localImag");

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

    </script>
</head>

<body>
<a href="javascript:;" class="file" id="localImag">
    <input type="file" name="" id="upload" onchange="setImagePreview(this.value,'pic')">
    <img src="./image/spare.png" id="pic">
</a>
</body>
</html>
网友评论