想在按下上傳之前先看看圖片長怎樣?HTML5 的 File API 加上 createObjectURL 就能在本機完成,不必先跑一趟伺服器。
<div class="addpic"> <button>添加圖片</button> <form> <input id="logoimg" class="addlogo" type="file" multiple accept="image/*" name="logo"> </form> </div> <img id="showlogo" src="" alt="">
這裡有個常見手法:真正接收點擊的是 input[type=file],只是我們把它設成透明並蓋在按鈕上方,視覺上看起來就像在點按鈕。把 accept 設為 image/* 可以讓檔案選擇器只列出圖片類檔案。
.addpic{
position:relative;
margin-left:100px;
width:95px;
height:30px;
}
.addlogo {
background: none repeat scroll 0 0 rgba(0, 0, 0, 0);
cursor: pointer;
font-size: 30px;
opacity: 0;
position: absolute;
right: 0;
top: 0;
z-index: 10;
}
關鍵是 opacity: 0 加上絕對定位與 z-index,讓 input 隱形地覆蓋在按鈕上,同時仍可接收點擊。
function readFiles(evt){
var files = evt.target.files;
if(!files){
console.log("the file is invalid");
return;
}
for(var i=0, file; file=files[i]; i++){
var imgele = new Image();
var thesrc = window.URL.createObjectURL(file);
imgele.src = thesrc;
imgele.onload = function(){
$("#showlogo").attr("src", this.src);
}
}
}
$(document).ready(function(){
$("#logoimg").change(function(e){
readFiles(e)
});
});
window.URL.createObjectURL(file) 會產生一個指向本機檔案的暫存網址,這是讀取大檔時比 Base64 更省記憶體的做法。URL.revokeObjectURL(url) 釋放。這個暫存物件不會自動消失,長時間開著的頁面若反覆選檔,記憶體會慢慢被吃掉。#showlogo,所以多選時最終只會顯示最後一張。要顯示全部,應該改成先清空容器再逐一 append。accept="image/* 只是選擇器上的提示,真正的型別檢查仍建議在程式中判斷 file.type。