首先判断IE或是Firefox,chrome。本文只测试了IE8中和Firefox,chrome是不一样的。
判断是否IE:
if(-[1,]){//判断浏览器不是IE
//alert((-[1,]?"不":"")+"是ie");
var oFReader = new FileReader();
oFReader.onload = function(e) {
document.getElementById("imageMark").src = e.target.result;
}
if (document.getElementById("fileMark").files.length === 0) { return; }
var oFile = document.getElementById("fileMark").files[0];
oFReader.readAsDataURL(oFile);
imageStatus = true;
}else{//判断浏览器是IE
......
}
下面是两个火狐下上传的例子:
例一:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta content="text/html; charset=GBK" http-equiv="Content-Type" />
<title>Image preview example</title>
<style type="text/css">
div {width:100px;height:100px;border: 1px #A3BFE7 solid;}
img {width:atuo;height:atuo;}
</style>
<script type="text/javascript">
function viewPic() {
var oFReader = new FileReader();
oFReader.onload = function(e) {
document.getElementById("uploadPreview").src = e.target.result;
}
if (document.getElementById("uploadImage").files.length === 0) { return; }
var oFile = document.getElementById("uploadImage").files[0];
oFReader.readAsDataURL(oFile);
}
</script>
</head>
<body>
<input id="uploadImage" type="file" name="myPhoto" onchange='viewPic();'/><br>
<img id="uploadPreview" src=""/>
</body>
</html>
例二:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img_prev').attr('src', e.target.result).width(150).height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="img_prev" src="#" alt="your image" />
</body>
</html>