图片预览

2016-08-09  本文已影响98人  赖床综合症

JS

//预览图片
function fileChange(imgId, fileId, fun) {
  
     var file = document.getElementById(fileId);
 
     var ext=file.value.substring(file.value.lastIndexOf(".")+1).toLowerCase();
     // gif在IE浏览器暂时无法显示
     if(ext!='png'&&ext!='jpg'&&ext!='jpeg'&&ext!='gif'&&ext!='bmp'){
         tipAlertShow("图片格式必须为png,jpg,jpeg,gif,bmp!");
         file.value='';
         return;
     }
     
     var pic = document.getElementById(imgId);//显示图片的img
     
     // IE浏览器
     if (document.all) {
      
         file.select();
         
         //ie9及以下,ie安全性问题会导致拒绝访问,需要失去焦点才能获取createRange
         file.blur();
         
         //fileObj.blur(); //不加上document.selection.createRange().text在ie9会拒绝访问
         // document.getElementById("imgCount").focus(); //参考http://gallop-liu.iteye.com/blog/1344778
          
         var reallocalpath = "";
         
         if(document.selection) {
          reallocalpath = document.selection.createRange().text;
         } else {
          reallocalpath = document.getSelection();
         }
     
         var ie6 = /msie 6/i.test(navigator.userAgent);
         // IE6浏览器设置img的src为本地路径可以直接显示图片
         if (ie6) pic.src = reallocalpath; 
         else { 
             // 非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片,但是可以通过滤镜来实现
             pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src=\"" + reallocalpath + "\")";
             // 设置img的src为base64编码的透明图片 取消显示浏览器默认图片
             pic.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
            
         }
 
         if (fun != null) {
             fun();
         };
     }else{
         html5Reader(file, imgId, fun);
     }
     
}
 
//展示图片
function html5Reader(imgFile, imgId, fun){ 
     var file = imgFile.files[0]; 
     var reader = new FileReader(); 
     reader.readAsDataURL(file); 
     reader.onload = function(e){ 
         var pic = document.getElementById(imgId);
         pic.src=this.result;
 
         if (fun != null) {
             fun();
         };
     } 
}

HTML

<form enctype="multipart/form-data" name="form1">
    上传文件:<input id="f" type="file" name="f" onchange="change('preview', 'f', '')" />

    预览:<img id="preview" alt="" name="pic" />
</form>
上一篇下一篇

猜你喜欢

热点阅读