「選好檔案還沒上傳,就先看到縮圖」是很常見的體驗。要做到這件事,得先解決一個難題:瀏覽器基於隱私,不讓 JavaScript 讀取本機檔案的實際路徑。因此這個元件必須针对不同瀏覽器走不同的路。
| 模式 | 適用環境 | 做法 |
|---|---|---|
filter | IE 7 / IE 8 | 用 document.selection.createRange().text 取得路徑,再搭配 AlphaImageLoader 濾鏡顯示 |
domfile | Firefox 3+ | 用 file.files[0].getAsDataURL() 直接取得 base64 |
remote | Opera / Chrome / Safari | 把圖片先上傳到伺服器,再由伺服器回傳可顯示的網址 |
simple | 其他 | 直接把 input.value 塞給 img(通常不會成功) |
var ImagePreview = function (file, img, options) {
this.file = $(file); // 檔案物件
this.img = $(img); // 預覽圖片物件
this._preload = null; // 預載圖片物件
this._data = ""; // 圖像資料
this._upload = null; // remote 模式的上傳物件
var opt = this._setOptions(options);
this.action = opt.action;
this.timeout = opt.timeout;
this.ratio = opt.ratio;
this.maxWidth = opt.maxWidth;
this.maxHeight = opt.maxHeight;
this.onCheck = opt.onCheck;
this.onShow = opt.onShow;
this.onErr = opt.onErr;
// 依模式選擇資料取得程序與顯示程序
this._getData = this._getDataFun(opt.mode);
this._show = opt.mode !== "filter" ? this._simpleShow : this._filterShow;
};
// 依瀏覽器自動判定模式
ImagePreview.MODE = $B.ie7 || $B.ie8 ? "filter" :
$B.firefox ? "domfile" :
$B.opera || $B.chrome || $B.safari ? "remote" : "simple";
_setOptions: function (options) {
this.options = {
mode: ImagePreview.MODE, // 預覽模式
ratio: 0, // 自訂比例
maxWidth: 0, // 縮圖寬度
maxHeight: 0, // 縮圖高度
onCheck: function () {}, // 檢測時執行
onShow: function () {}, // 顯示時執行
onErr: function () {}, // 出錯時執行
action: undefined, // remote 模式的上傳位址
timeout: 0 // 逾時秒數,0 為不限
};
return $.extend(this.options, options || {});
}
// 開始預覽
preview: function () {
if (this.file && false !== this.onCheck()) {
this._preview(this._getData());
}
},
// 空值或相同的值不重複處理
_preview: function (data) {
if (!!data && data !== this._data) {
this._data = data;
this._show();
}
},
// 依縮圖上限算出縮放比例並顯示
_imgShow: function (src, width, height) {
var img = this.img, style = img.style;
var ratio = Math.max(0, this.ratio) || Math.min(1,
Math.max(0, this.maxWidth) / width || 1,
Math.max(0, this.maxHeight) / height || 1
);
style.width = Math.round(width * ratio) + "px";
style.height = Math.round(height * ratio) + "px";
img.src = src;
this.onShow();
}
比例計算很值得學:如果指定了 ratio 就直接用;否則分別算出寬與高的可用比例,取最小的那一個並限制不超過 1,這樣就能保證圖片完整塞進指定框內且不會被放大變模糊。
_filterPreload: function () {
if (!this._preload) {
var preload = this._preload = document.createElement("div");
// 隱藏並掛上濾鏡,用來量出圖片原始尺寸
$D.setStyle(preload, {
width: "1px", height: "1px",
visibility: "hidden", position: "absolute",
left: "-9999px", top: "-9999px",
filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image')"
});
var body = document.body;
body.insertBefore(preload, body.childNodes[0]);
}
}
_filterShow: function () {
this._filterPreload();
var preload = this._preload;
var data = this._data.replace(/[)'"%]/g, function (s) { return escape(escape(s)); });
try {
preload.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = data;
} catch (e) { this._error("filter error"); return; }
this.img.style.filter =
"progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src=\"" + data + "\")";
this._imgShow(ImagePreview.TRANSPARENT, preload.offsetWidth, preload.offsetHeight);
}
IE 的做法是先用一個隱藏的 div 承載濾鏡,讀出它的 offsetWidth/offsetHeight 取得原始尺寸,再用 sizingMethod='scale' 讓濾鏡自行縮放,最後把 img 的 src 換成一張 1×1 的透明圖。
ImagePreview.TRANSPARENT = $B.ie7 || $B.ie6 ?
"mhtml:" + document.scripts[document.scripts.length - 1].getAttribute("src", 4) + "!blankImage" :
"data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";
舊 IE 不支援 data URI,因此用 mhtml 封包協定配合外部檔案;現代瀏覽器則直接用 base64 的透明 GIF。
<input id="idFile" type="file" name="pic" />
<img id="idImg" alt="" src="https://www.jb51.net/" />
<script>
var ip = new ImagePreview($$("idFile"), $$("idImg"), {
maxWidth: 200,
maxHeight: 2000,
action: "ImagePreview.ashx"
});
ip.img.src = ImagePreview.TRANSPARENT;
ip.file.onchange = function () { ip.preview(); };
</script>
_getDataFun(mode) 回傳不同的函式,把「怎麼取資料」與「怎麼用資料」分開,各瀏覽器的差異被收在同一個 switch 裡。onCheck/onShow/onErr 三個回呼,讓呼叫端可以攔截流程。onCheck 回傳 false 就能取消預覽,這是很實用的設計。dispose() 逐一清空 upload、preload 與 DOM 參照,避免記憶體殘留,這點很多老程式都沒做。這整套四模式的分支邏輯,在今日已經完全被標準 API 取代:
const input = document.querySelector("#idFile");
const img = document.querySelector("#idImg");
input.addEventListener("change", () => {
const file = input.files[0];
if (!file) return;
const url = URL.createObjectURL(file); // 產生 blob: URL
img.src = url;
img.onload = () => URL.revokeObjectURL(url); // 用完記得釋放
});
URL.createObjectURL() 自 IE 10 起全面支援,能安全地把本機檔案轉成可顯示的暫存網址,不必上傳、不必 base64、也不會讀到真實路徑。若還想顯示原始尺寸與檔案大小,file.size 與 img.naturalWidth 就能取得。記得在圖片不再使用時呼叫 revokeObjectURL 釋放記憶體,這是唯一的注意事項。