记录一下: 火狐 IE 实现图片本地预览 demo

牛人详细分析:http://www.cnblogs.com/cloudgamer/archive/2009/12/22/ImagePreview.html

图片上传预览是一种在图片上传之前对图片进行本地预览的技术。
使用户选择图片后能立即查看图片,而不需上传服务器,提高用户体验。
但随着浏览器安全性的提高,要实现图片上传预览也越来越困难。
不过群众的智慧是无限的,网上已经有很多变通或先进的方法来实现。
例如ie7/ie8的滤镜预览法,firefox 3的getAsDataURL方法。
但在opera、safari和chrome还是没有办法实现本地预览,只能通过后台来支持预览

demo:

<html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>图片上传预览ie6,7,8, firefox</title>
<script language="javascript">
  function checkPic(){
   var picPath=document.getElementById("picPath").value;
      var type=picPath.substring(picPath.lastIndexOf(".")+1,picPath.length).toLowerCase();
   if(type!="jpg"&&type!="bmp"&&type!="gif"&&type!="png"){
    alert("请上传正确的图片格式");
    return false;
   }
   return true;
  }
   //图片预览
  function PreviewImage(divImage,upload,width,height) { 
  if(checkPic()){
   try{
    var imgPath;
     //图片路径    
         var Browser_Agent=navigator.userAgent;
         //判断浏览器的类型  
          if(Browser_Agent.indexOf("Firefox")!=-1){
               //火狐浏览器
              imgPath = upload.files[0].getAsDataURL();              
              document.getElementById(divImage).innerHTML = "<img id='imgPreview' src='"+imgPath+"' width='"+width+"' height='"+height+"'/>";
         }else{
             //IE浏览器
             var Preview = document.getElementById(divImage);
             Preview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = upload.value;
             Preview.style.width = width;
             Preview.style.height = height;
   } 
  }catch(e){
    alert("请上传正确的图片格式");
   }
 }
 }
</script>
</head>

<body>
  产品图片
     <input type="file" id="picPath" name="doc" onChange="PreviewImage('Preview',this,78,38);" />
<div id="Preview" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);">   
    </div>
</body>
</html>

原文地址:https://www.cnblogs.com/drawwindows/p/2301750.html