版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ccutsoft20144264/article/details/51779541
最近在做一个.net mvc的网站,想让用户在网页中上传图片的过程中预览图片,本以为很简单,以为可以直接在html中解决,百度了很多才发现貌似挺麻烦,综合一些大神的回答,总结了一下。
完成此类操作,一般都用到了FileReader功能,从文件中读取数据保存到JS变量中;HTML DOM getElementById方法,可返回对拥有指定ID的第一个对象的引用。
Code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
<script type="text/javascript">
function getFileUrl(sourceId) {
var url;
if (navigator.userAgent.indexOf("MSIE")>=1) { // IE
url = document.getElementById(sourceId).value;
} else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox
url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
} else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome
url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
}
return url;
}
function preImg(sourceId, targetId) {
var url = getFileUrl(sourceId);
var imgPre = document.getElementById(targetId);
imgPre.src = url;
}
</script>
</head>
<body>
<div>
<br />
<br />
<a>上传者:<input type="text" /></a>
<br />
<br />
<form action="">
<input type="file" name="imgOne" id="imgOne" onchange="preImg(this.id,'photo');" />
<br />
<br />
<img id="photo" src="" width="300px" height="300px" style="display: block;" />
</form>
</div>
</body>
</html>