很多後台介面都會用到「選圖 → 立刻看到預覽」的功能。這個效果不需要任何伺服器端支援,只要一個 <input type="file"> 加上 onchange 事件,就能在使用者挑好檔案的當下把圖片顯示出來。
當檔案被選取時,file 控制項的 value 就是該圖片的本機路徑。我們把這個路徑直接指定給 <img> 的 src,圖片便會出現在頁面上;同時把 img 的 style.display 設為空字串,讓原本隱藏的預覽圖顯示出來,並加上 1 像素的邊框方便辨識。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>帶有圖片預覽功能的上傳表單</title>
<script>
function viewmypic(mypic, imgfile) {
if (imgfile.value) {
mypic.src = imgfile.value;
mypic.style.display = "";
mypic.border = 1;
}
}
</script>
</head>
<body>
<center>
<form>
<input name="imgfile" type="file" id="imgfile" size="40" onchange="viewmypic(showimg, this.form.imgfile);" />
<br />
</form>
<img name="showimg" id="showimg" src="" style="display:none;" alt="預覽圖片" />
<br />
</center>
</body>
</html>
整個功能的核心只有 viewmypic 這個函式,它接受兩個參數:預覽用的 img 元素,以及檔案控制項本身。onchange 觸發時傳入的是 this.form.imgfile,也就是使用者剛選好的那一支檔案。
要注意的是,這種做法顯示的是使用者本機的檔案路徑,僅能作為「送出前的確認預覽」,圖片實際上傳後仍須由伺服器回傳真正的網址來更新預覽。此外,為了相容性與安全性,正式環境建議改用 newer 的 File API(URL.createObjectURL)來產生預覽,並在伺服器端做好檔案類型與大小的驗證。