DIV CSS 佈局教程網

用 JavaScript 取得使用者本機圖片並即時預覽
編輯:關於JavaScript     

表單的 file 控制項預設只會顯示檔名,若想在選檔後馬上預覽圖片,就得取得該檔案的可用來源。以下範例針對 IE 與 Firefox 分別處理。

完整程式碼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>get file input full path</title>
<script language='javascript'>
function getFullPath(obj)
{
    if (obj)
    {
        // IE:透過 selection 取得完整路徑
        if (window.navigator.userAgent.indexOf("MSIE") >= 1)
        {
            obj.select();
            return document.selection.createRange().text;
        }
        // Firefox:用 File API 轉成 data URL
        else if (window.navigator.userAgent.indexOf("Firefox") >= 1)
        {
            if (obj.files)
            {
                return obj.files.item(0).getAsDataURL();
            }
            return obj.value;
        }
        return obj.value;
    }
}
</script>
</head>
<body>
<input type="file" onchange="document.getElementById('img').src = getFullPath(this);" />
<img id="img" />
</body>
</html>

把上面的程式碼存成 htm 檔後執行即可。

兩條路徑背後的差異

IE 的做法是靠 document.selection.createRange().text 取得的完整本機路徑,這在早期 IE 上確實可行。Firefox 則走 File API,用 getAsDataURL() 把圖片內容編碼成 data: 協定的字串,直接塞給 img.src 就能顯示。

兩者的本質差別在於「路徑」與「內容」:前者拿到的是字串路徑,後者拿到的是圖片本身的編碼資料。這個差異也決定了它們在安全性上的分歧——基於隱私考量,瀏覽器早已全面禁止網頁讀取使用者的真實檔案系統路徑,IE 那種做法不復存在。

現代的標準寫法

今天要實作同樣的功能,用 FileReader 就是跨瀏覽器的正解:

<input type="file" accept="image/*" onchange="preview(this.files[0])">
<img id="img" alt="預覽">

<script>
function preview(file) {
    var reader = new FileReader();
    reader.onload = function(e) {
        document.getElementById('img').src = e.target.result;
    };
    reader.readAsDataURL(file);
}
</script>

若只是要預覽而不上傳,還可以用更省資源的 URL.createObjectURL(file) 產生 blob URL,用完記得呼叫 URL.revokeObjectURL() 釋放。兩種方式都不需要判斷瀏覽器,也不必具備任何伺服器端支援。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved