1 <div id="divPreview"> 2 <img id="imgHeadPhoto" src="Images/Headphoto/noperson.jpg" style=" 160px; height: 170px;border: solid 1px #d2e2e2;" alt="" /> 3 </div> 4 <input type="file" id="fuHeadPhoto" onchange="PreviewImage(this,'imgHeadPhoto','divPreview')"> 5 <script type="text/javascript"> 6 //js本地图片预览,兼容ie[6-9]、火狐、Chrome17+、Opera11+、Maxthon3、360浏览器 7 function PreviewImage(fileObj,imgPreviewId,divPreviewId){ 8 var allowExtention=".jpg,.bmp,.gif,.png";//允许上传文件的后缀名document.getElementById("hfAllowPicSuffix").value; 9 var extention=fileObj.value.substring(fileObj.value.lastIndexOf(".")+1).toLowerCase(); 10 var browserVersion= window.navigator.userAgent.toUpperCase(); 11 if(allowExtention.indexOf(extention)>-1){ 12 if(fileObj.files){//兼容chrome、火狐7+、360浏览器5.5+等,应该也兼容ie10,HTML5实现预览 13 if(window.FileReader){ 14 var reader = new FileReader(); 15 reader.onload = function(e){ 16 document.getElementById(imgPreviewId).setAttribute("src",e.target.result); 17 } 18 reader.readAsDataURL(fileObj.files[0]); 19 }else if(browserVersion.indexOf("SAFARI")>-1){ 20 alert("不支持Safari浏览器6.0以下版本的图片预览!"); 21 } 22 }else if (browserVersion.indexOf("MSIE")>-1){//ie、360低版本预览 23 if(browserVersion.indexOf("MSIE 6")>-1){//ie6 24 document.getElementById(imgPreviewId).setAttribute("src",fileObj.value); 25 }else{//ie[7-9] 26 fileObj.select(); 27 if(browserVersion.indexOf("MSIE 9")>-1) 28 fileObj.blur();//不加上document.selection.createRange().text在ie9会拒绝访问 29 var newPreview =document.getElementById(divPreviewId+"New"); 30 if(newPreview==null){ 31 newPreview =document.createElement("div"); 32 newPreview.setAttribute("id",divPreviewId+"New"); 33 newPreview.style.width = document.getElementById(imgPreviewId).width+"px"; 34 newPreview.style.height = document.getElementById(imgPreviewId).height+"px"; 35 newPreview.style.border="solid 1px #d2e2e2"; 36 } 37 newPreview.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')"; 38 var tempDivPreview=document.getElementById(divPreviewId); 39 tempDivPreview.parentNode.insertBefore(newPreview,tempDivPreview); 40 tempDivPreview.style.display="none"; 41 } 42 }else if(browserVersion.indexOf("FIREFOX")>-1){//firefox 43 var firefoxVersion= parseFloat(browserVersion.toLowerCase().match(/firefox/([d.]+)/)[1]); 44 if(firefoxVersion<7){//firefox7以下版本 45 document.getElementById(imgPreviewId).setAttribute("src",fileObj.files[0].getAsDataURL()); 46 }else{//firefox7.0+ 47 document.getElementById(imgPreviewId).setAttribute("src",window.URL.createObjectURL(fileObj.files[0])); 48 } 49 }else{ 50 document.getElementById(imgPreviewId).setAttribute("src",fileObj.value); 51 } 52 }else{ 53 alert("仅支持"+allowExtention+"为后缀名的文件!"); 54 fileObj.value="";//清空选中文件 55 if(browserVersion.indexOf("MSIE")>-1){ 56 fileObj.select(); 57 document.selection.clear(); 58 } 59 fileObj.outerHTML=fileObj.outerHTML; 60 } 61 } 62 </script>