關於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>複製代碼