亲宝软件园·资讯

展开

JS上传前预览图片实例

人气:0

预览图片的js代码:

复制代码 代码如下:

<script type="text/javascript">
        function setImagePreview(docObj,localImagId,imgObjPreview)
        {
            if(docObj.files && docObj.files[0])
            {
                //火狐下,直接设img属性
                imgObjPreview.style.display = 'block';
                imgObjPreview.style.width = '300px';
                imgObjPreview.style.height = '200px';                   


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

                //必须设置初始大小
                localImagId.style.width = "300px";
                localImagId.style.height = "200px";

                //图片异常的捕捉,防止用户修改后缀来伪造图片
                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>

fileupload控件及用来预览图片的image:

复制代码 代码如下:

<div id="localImag"  style="width: 300px; height: 200px">
   <img id="preview" alt="预览图片" src="//www.qb5200.com/images/logo.gif" width="300px" height="200px" />
</div>
   <asp:FileUpload ID="PicLoad" Width="300px" runat="server" onchange="javascript:setImagePreview(this,localImag,preview);">
   </asp:FileUpload>

  


功能很简单,代码也很易懂,相信不用我多废话大家也能看懂吧。感觉写这样的文章,真的没啥好说的,不多说,还是把重点放在代码上吧。

加载全部内容

相关教程
猜你喜欢
用户评论