体式格局一:更适合H5页面,兼容ie10+,图片base64显现,主要功能点是FileReader和readAsDataURL
简约代码以下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>files-h5</title>
</head>
<body>
<input type="file" id="file" onchange="showPreview(this, 'portrait')" />
<img src="" id="portrait" style="width: 200px; height: 200px; display: block;" />
<script>
function showPreview(source, imgId) {
var file = source.files[0];
if(window.FileReader) {
var fr = new FileReader();
fr.onloadend = function(e) {
document.getElementById(imgId).src = e.target.result;
}
fr.readAsDataURL(file);
}
}
</script>
</body>
</html>
体式格局二:更适合PC端,兼容ie7+,主要功能点是window.URL.createObjectURL
简约代码以下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>files-pc</title>
</head>
<body>
<input type="file" id="file" onchange="showPreview(this.id,'portrait')" />
<img src="" id="portrait" style="width: 200px; height: 200px; display: block;" />
<script type="text/javascript">
/* 图片预览 */
function showPreview(fileId, imgId) {
var file = document.getElementById(fileId);
var ua = navigator.userAgent.toLowerCase();
var url = '';
if(/msie/.test(ua)) {
url = file.value;
} else {
url = window.URL.createObjectURL(file.files[0]);
}
document.getElementById(imgId).src = url;
}
</script>
</body>
</html>