关于FileReader的讲解能够看这里javascript
关于URL.createObjectURL方法的讲解和应用能够看这里css
demo地址html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>preview</title>
<style> * { box-sizing: border-box; } .section { margin: 20px auto; width: 500px; border: 1px solid #666; text-align: center; } .preview { width: 100%; margin-top: 10px; padding: 10px; min-height: 100px; background-color: #999; } .preview img, .preview video { width: 100%; } </style>
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="section">
<p>方案1</p>
<input class="upload" type="file" onchange=onUpload1(this.files[0])>
<div class="preview preview1"></div>
</div>
<div class="section">
<p>方案2</p>
<input class="upload" type="file" onchange=onUpload2(this.files[0])>
<div class="preview preview2"></div>
</div>
<script> function onUpload1 (file) { var fr = new FileReader(); fr.readAsDataURL(file); // 将文件读取为Data URL fr.onload = function(e) { var result = e.target.result; if (/image/g.test(file.type)) { var img = $('<img src="' + result + '">'); $('.preview1').html('').append(img); } else if (/video/g.test(file.type)) { var vidoe = $('<video controls src="' + result + '">'); $('.preview1').html('').append(vidoe); } } } function onUpload2 (file) { var blob = new Blob([file]), // 文件转化成二进制文件 url = URL.createObjectURL(blob); //转化成url if (/image/g.test(file.type)) { var img = $('<img src="' + url + '">'); img[0].onload = function(e) { URL.revokeObjectURL(this.src); // 释放createObjectURL建立的对象 } $('.preview2').html('').append(img); } else if (/video/g.test(file.type)) { var video = $('<video controls src="' + url + '">'); $('.preview2').html('').append(video); video[0].onload = function(e) { URL.revokeObjectURL(this.src); // 释放createObjectURL建立的对象 } } } </script>
</body>
</html>复制代码