创作背景:
公司项目都是依赖于Ie浏览器,好多的技术都是不支持ie,对于ie,尤其是ie9以下,必须特别处理。
html:
<div style="width: 103px;height: 130px;border: solid 1px #CDCDCD;border-radius: 8px;margin: 0 auto;"> <img id="nophoto" style="width: 100%;height: 100%;" src="../templates/tpl/image/images/photo.png" > </div> <span id="uploadBtnBox"> <input id="fileBtn" οnchange='change()' name="file" type="file" size="10"> <a id="linkBtn">浏览</a> </span>
js:这种方式给后端传递的是file对象。function change(){ //获取需要处理的DOM对象 var pic = document.getElementById("nophoto"), file = document.getElementById("fileBtn"); //获取图片后缀 var ext = file.value.substring(file.value.lastIndexOf(".")+1).toLowerCase(); //gif在IE浏览器暂时无法显示 if(ext != 'png' && ext != 'jpg' && ext != 'jpeg'){ alert("图片的格式必须为png或者jpg或者jpeg格式!"); return; } //判断ie类型 var isIE = navigator.userAgent.match(/MSIE/) != null, isIE6 = navigator.userAgent.match(/MSIE 6.0/) != null; //根据浏览器的类型进行操作方式的选择 if(isIE) { //选中表单提交中的file对象,即获得焦点,可以继续保持 file.select(); //因为ie9安全级别高,需要模拟让其失去焦点 //file.blur(); //获取文件的本地地址 var reallocalpath = document.selection.createRange().text; //document.selection.createRange(); --->window.getSelection(); [ie11] //alert(reallocalpath); //IE6浏览器设置img的src为本地路径可以直接显示图片 if(isIE6){ //加载预览图 pic.src = reallocalpath; }else{ //alert('this'); //非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片,但是可以通过滤镜来实现 document.getElementById("file1").value=reallocalpath; pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src=\"" + reallocalpath + "\")"; //pic.style.cssText="display: block;width:106px ;height: 130px;margin: 0 auto;"; //设置img的src为base64编码的透明图片 取消显示浏览器默认图片 pic.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; //alert(reallocalpath); pic.src=reallocalpath; } }else { html5Reader(file); } } //html5预览图片方法 function html5Reader(file){ var file = file.files[0]; var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(){ var pic = document.getElementById("nophoto"); pic.src = this.result; } reader.readAsDataURL(file); }