之前做圖片、視訊上傳預覽常用的方案是先把檔案上傳到伺服器,等伺服器返回檔案的地址後,再把該地址字串賦給img或video的src屬性,這才實現所謂的檔案預覽。實際上這只是檔案“上傳後再預覽”,這既浪費了使用者的時間,也浪費了不可輕視的流量。
最近上網查資料才知道其實可以很輕鬆地實現“上傳前預覽”。實現方法有兩種:FileReader和URL.createObjectURL。
關於FileReader的講解可以看這裡
關於URL.createObjectURL方法的講解和應用可以看這裡
直接上程式碼:
<!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>複製程式碼