createObjectURL方法 實現本地圖片預覽


ie6 可以直接顯示本本地路徑的圖片 如: <img src="file://c:/3.jpg" />  ~~~網上都說ie7就不支持這種文件系統路徑的url,但測試 xp ie8還是可以的

ie8+ alphaImageLoader濾鏡方式加載本地路徑的圖片

chrome, firefox, 用dataUrl  或 createObjectURL方法實現

例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <title>get file input full path</title>
    <script type="text/javascript" language='javascript'>
        function getFullPath(obj) {
            var newPreview = document.getElementById("img");
            if (obj) {
                //ie
                if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
                    obj.select();
                    newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);";
                    newPreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = document.selection.createRange().text;

                    return;
                }
                //firefox
                else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
                    if (obj.files) {
                        newPreview.src = window.URL.createObjectURL(obj.files.item(0));

                        return;
                    }
                    newPreview.src = obj.value;

                    return;
                }
                newPreview.src = obj.value;

                return;
            }
        }
    </script>
</head>
<body>
    <input type="file" onchange="getFullPath(this);" />
    <img id="img" alt="" style="width:200px; height:200px;" src="你自己的透明圖片"/>
</body>
</html>
 

 

 

然后 我們來看看 window.URL.createObjectURL() 到底是什么

window.URL.createObjectURL

概述

創建一個新的對象URL,該對象URL可以代表某一個指定的File對象或Blob對象.

語法

objectURL = window.URL.createObjectURL(blob);
  • blob參數是一個File對象或者Blob對象.
  • objectURL是生成的對象URL.通過這個URL,可以獲取到所指定文件的完整內容.

示例

查看使用對象URL顯示圖片.

附注

在每次調用createObjectURL()方 法的時候,都會創建一個新的對象URL,即使參數中的這個對象已經有了自己的對象URL.在你不需要這些對象URL的時候,你應該通過調用 window.URL.revokeObjectURL()方法來釋放它們所占用的內容.雖然即使你不主動釋放它們,瀏覽 器也會在當前文檔被卸載的時候替你釋放,不過,考慮到更好的性能和更少的內存占用,你應該在安全的時候主動施放它們.

瀏覽器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 8 4 10 12 Nightly build


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM