JS 實現圖片下載

 download 屬性是HTML5中新增的 <a> 標籤屬性,但在IE低版本瀏覽器中不識別此屬性,需要區分瀏覽器並針對性處理,還有就是如果動態的更新圖片下載地址,瀏覽器的安全機制會阻止觸發點擊事件。下面來看示例

定義和用法

download 屬性定義了下載鏈接的地址。

href 屬性必須在 <a> 標籤中指定。

屬性同樣可以指定下載文件的名稱。文件名稱沒有限定值,瀏覽器會自動在文件名稱末尾添加該下載文件的後綴 (.img, .pdf, .txt, .html, 等)。

通過<a>鏈接來實現圖片下載

    <a href="down.jpg" download="downImage">
      <img src="down.jpg" alt="">
    </a>

這只是簡單的示例,如果要通過ajax動態獲取下載地址並觸發下載時就會有問題。


<!DOCTYPE html>
<html lang="en">
<div>
<table id="userTable" class="table" data-loading="userLoading">
        <thead>
             <tr>
                  <th>圖片名稱</th>
                  <th>操作</th>
             </tr>
         </thead>
             <tbody>
                <tr>
                 <td>測試圖片</td>
                <td class="itemActions" data-id=8>                          
                    <a class="btn btn-table down" title="下載" >下載</a>
                </td>
              </tr>
             </tbody>
</table>
<div>
</html>
<script>

    // 下載
    $("#userTable tbody").on('click', '.itemActions .down', function () {
        var id = $(this).parent().data('id');
        axios.post('後臺接口地址', {
            id: id,
        }).then(x => {
            if (x.data.success) {
                let imageUrl = x.data.instance;
                if (browserIsIe()) {
                    //調用創建iframe的函數
                    createIframe(imageUrl);
                } else {                   
                    //創建原生a標籤實現動態Img地址及下載觸發 
                   let tempa= document.createElement('a');
                   tempa.href=imageUrl;
                   tempa.download='download';
                   document.body.append(tempa);
                   tempa.click();
                   tempa.remove();                                   
                }
            } else {
                $.growl.error({
                    message: x.data.errorMsg,
                });
            }
        })
    });

   //判斷是否爲Trident內核瀏覽器(IE等)函數
    function browserIsIe() {
        if (!!window.ActiveXObject || "ActiveXObject" in window) {
            return true;
        }
        else {
            return false;
        }
    }
    //創建iframe並賦值的函數,傳入參數爲圖片的src屬性值.
    function createIframe(imgSrc) {
        //如果隱藏的iframe不存在則創建
        if ($("#IframeReportImg").length === 0) {
            $('<iframe style="display:none;" id="IframeReportImg" name="IframeReportImg" οnlοad="downloadImg();" width="0" height="0" src="about:blank"></iframe>').appendTo("body");
        }
        //iframe的src屬性如不指向圖片地址,則手動修改,加載圖片
        if ($('#IframeReportImg').attr("src") != imgSrc) {
            $('#IframeReportImg').attr("src", imgSrc);
        } else {
            //如指向圖片地址,直接調用下載方法
            downloadImg();
        }
    }
    //下載圖片的函數
    function downloadImg() {
        //iframe的src屬性不爲空,調用execCommand(),保存圖片
        if ($('#IframeReportImg').src != "about:blank") {
            window.frames["IframeReportImg"].document.execCommand("SaveAs");
        }
    }
</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章