Skip to content

Instantly share code, notes, and snippets.

@moodpo
Created April 14, 2014 08:44
Show Gist options
  • Save moodpo/10628720 to your computer and use it in GitHub Desktop.
Save moodpo/10628720 to your computer and use it in GitHub Desktop.
Javascript/js兼容各个浏览器的本地图片上传即时预览效果(仅预览)
function change() {
var pic = document.getElementById("preview");
var file = document.getElementById("f");
var ext=file.value.substring(file.value.lastIndexOf(".")+1).toLowerCase();
// gif在IE浏览器暂时无法显示
if(ext!='png'&&ext!='jpg'&&ext!='jpeg'){
alert("文件必须为图片!"); return;
}
// IE浏览器
if (document.all) {
file.select();
var reallocalpath = document.selection.createRange().text;
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='image',src=\"" + reallocalpath + "\")";
// 设置img的src为base64编码的透明图片 取消显示浏览器默认图片
pic.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
}
}else{
html5Reader(file);
}
}
function html5Reader(file){
var file = file.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e){
var pic = document.getElementById("preview");
pic.src=this.result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment