最近工作交接涉及到图片上传,在Google,Firefox,ie11浏览器都很好的显示了本地图片的预览。可是项目要求ie最低版本为ie9,只好卸了11换个9果然出了问题,图片显示不出来了。但是保存完再从服务器上取ie9也能很好的显示,于是便想到先上传到浏览器再取回(但是有点占用网络资源)。那直接js来处理呢,搜索了一番这,似乎可以用滤镜来实现。
HTML代码:
<form name="form" id="form" enctype="multipart/form-data">
<input type="file" id="logo" name="logo" onChange="logoShow(this.value)" /></td>
<img id="showLogo" src=""></img>
</form>
js代码:
if(navigator.userAgent.indexOf("MSIE 9.0")>0){//判断ie浏览器版本
var pic = document.getElementById("showLogo"),
file = document.getElementById("logo");
file.select();
//由于ie9的安全性,若没有focus()聚焦到其他button,div等,document.selection.createRange().text将会报错
//(这里的save是一个button,若focus到div这个div需要至少有1px)
document.getElementById("save").focus();
//file.blur();
var reallocalpath = document.selection.createRange().text;
pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src=\"" + reallocalpath + "\")";//增加滤镜
//这里设置预览图片pic的大小
pic.style.width = "180px";
pic.style.height = "130px";
// 设置img的src为base64编码的透明图片 取消显示浏览器默认图片
pic.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
}else{
//其他浏览器
document.getElementById("showLogo").src =getFileUrl("logo");
}
function getFileUrl(fileName){
var url ;
if (navigator.userAgent.indexOf("MSIE")>=1) {
url = document.getElementById(sourceId).value; // IE10,11可以使用这种方式
} else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox
url = window.URL.createObjectURL(document.getElementById(fileName).files.item(0));
} else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome
url = window.URL.createObjectURL(document.getElementById(fileName).files.item(0));
} else{
url = window.URL.createObjectURL(document.getElementById(fileName).files.item(0));
}
return url;
}
参考资源:
http://blog.youkuaiyun.com/yippeelyl/article/details/39324027
http://www.myexception.cn/database/628584.html