javascript实现IE,firefox客户端图片预览

  javascript实现IE,firefox客户端图片预览,测试浏览器:IE6~8,firefox4.0。

 

  google的chrome,safari,opera浏览器需要上传图片才行,这个不在讨论范围,上传后也变简单多了,将表单自动提交到隐藏iframe实现无刷新上传图片文件后,在服务器端保存图片然后返回路径,具体参考这篇文章:ajax无刷新上传文件,使用iframe模仿

 

  原理:由于IE7+的安全性问题,直接设置img的src也无法加载本地图片,但是滤镜没有这个问题,所以可以通过设置滤镜来实现IE7+浏览器本地图片预览效果。IE6就不用多少了,直接设置即可。

 

  IE7+获取file控件选择的文件路径:IE浏览器下获取file控件选择本地文件的路径

 

  示例代码如下

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>javascript实现IE,firefox客户端图片预览</title>
<script>
    var ie6 = /msie 6/i.test(navigator.userAgent);
    function change() {
        var pic = document.getElementById("pic");
        var file = document.getElementById("file1");
        if (document.all) {//IE浏览器
            file.select();
            var reallocalpath = document.selection.createRange().text//IE下获取实际的本地文件路径
            if (ie6) pic.src = reallocalpath; //IE6浏览器设置img的src为本地路径可以直接显示图片
            else { //非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片,但是可以通过滤镜来实现
                pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\"" + reallocalpath + "\")";
                pic.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';//设置img的src为base64编码的透明图片,要不会显示红xx
            }
        }
        else if (file.files) {//firefox浏览器
            if (file.files.item(0)) {
                url = file.files.item(0).getAsDataURL();
                pic.src = url;
            }
        }
    }
</script>
</head>
<body>
<form name="form1"  enctype="multipart/form-data"><table><tr>
          <td> 草图:</td>
          <td >
      <input type="file" name="file1" id="file1"  onchange="change()">
  </td>
 
<tr>
          <td>草图浏览:</td>
          <td>
      <img src="images/px.gif"  name="pic" id="pic" >
  </td></tr>
      </table> 
</form>
 
</body>
</html>

 

加支付宝好友偷能量挖...


原创文章,转载请注明出处:javascript实现IE,firefox客户端图片预览

评论(0)Web开发网
阅读(219)喜欢(0)JavaScript/Ajax开发技巧