使用a鏈接下載圖片


在做a鏈接下載圖片的時候遇到一個問題,在谷歌瀏覽器下只是新建了一個窗口,並沒有實現下載。瀏覽器版本信息

經過實測,在谷歌下a鏈接實現下載圖片必須具備兩個條件。1,必須在啟動服務,在服務器下運行。2,必須使用相對路徑。

下面附上兼容寫法代碼:

<ul>
    <li><span>本人照片:</span><img src="0.JPG" alt=""><a href="javascript:void(0);" onclick="down_img(this)">點擊下載</a>
        </li>
    <li><span>護照首頁:</span><img src="1.jpg"alt=""><a href="javascript:void(0);" onclick="down_img(this)">點擊下載</a>
        </li>
</ul>
    
function myBrowser() {
            var userAgent = navigator.userAgent; //取得瀏覽器的userAgent字符串
            var isOpera = userAgent.indexOf("Opera") > -1;
            if (isOpera) {
                return "Opera"
            }; //判斷是否Opera瀏覽器
            if (userAgent.indexOf("Firefox") > -1) {
                return "FF";
            } //判斷是否Firefox瀏覽器
            if (userAgent.indexOf("Chrome") > -1) {
                return "Chrome";
            }
            if (userAgent.indexOf("Safari") > -1) {
                return "Safari";
            } //判斷是否Safari瀏覽器
            if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
                return "IE";
            }; //判斷是否IE瀏覽器
            if (userAgent.indexOf("Trident") > -1) {
                return "Edge";
            } //判斷是否Edge瀏覽器
        }

    //②IE瀏覽器圖片保存(IE其實用的就是window.open)
    function SaveAs5(imgURL) {
        var oPop = window.open(imgURL, "", "width=1, height=1, top=5000, left=5000");
        for (; oPop.document.readyState != "complete";) {
            if (oPop.document.readyState == "complete") break;
        }
        oPop.document.execCommand("SaveAs");
        oPop.close();
    }

    //④點擊事件下載(只需更改圖片路徑即可)
    function down_img(a) {
        var osb = a;
        var sb = a.previousSibling.src;
        // console.log(sb)
        if (myBrowser() === "IE" || myBrowser() === "Edge") {
            //IE (瀏覽器)
            SaveAs5(sb);
        } else {
            //!IE (非IE)
            osb.href = sb;
            osb.download = "";
        }
    }

 

  


免責聲明!

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



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