function getPath()
{
//判断浏览器
var Sys = {};
var obj = document.getElementById("headImg");
var viewer = document.getElementById("viewImg");
var ua = navigator.userAgent.toLowerCase();
var s;
(s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
(s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
(s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
(s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
(s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
var path="";
if(Sys.ie<="6.0"){
//ie5.5,ie6.0
viewer.src = obj.value;
}else if(Sys.ie>="7.0"){
//ie7,ie8
obj.select();
//加上这一句防止报告安全问题
obj.blur();
viewer.src = document.selection.createRange().text;
}else if(Sys.firefox){
if (obj.files) {
var accept = ["image/png","image/jpeg","image/jpg","image/gif"];
if (accept.indexOf(obj.files[0].type) > -1) {
var reader = new FileReader();
reader.readAsDataURL(obj.files[0]);
//延迟一会等待文件读取完毕
var t = setTimeout(function(){
viewer.src = reader.result;
clearTimeout(t);
},100)
}
}
else
{
viewer.src = obj.value;
}
}else if(Sys.chrome){
viewer.src = obj.value;
}
}
<form>
<input type="file" id="headImg" />
<input id="btnOk" type="button" value="ok" onclick="getPath()"/>
<img src="http://blog.163.com/[email protected]/blog/" alt="view" id="viewImg" />
</form>
另一种:
var obj = document.getElementById("headImg");
var viewer = document.getElementById("viewImg");
obj.onchange=function(){
viewImg.value=getFullPath(this);
}
function getFullPath(obj){
if(obj)
{
//ie
if (window.navigator.userAgent.indexOf("MSIE")>=1)
{
obj.select();
return document.selection.createRange().text;
}
//firefox
else if(window.navigator.userAgent.indexOf("Firefox")>=1)
{
if(obj.files)
{
return obj.files.item(0).getAsDataURL();
}
return obj.value;
}
return obj.value;
}
}
参考资料:http://blog.sina.com.cn/s/blog_771875550100xjxh.html
http://blog.163.com/[email protected]/blog/static/678229742013119113558963/