前端頁面裏面的文件下載 兼容IE10+

頁面上一個下載按鈕,然後文件就嘩嘩的下載到你的本地了,這其中發生了什麼?

1.首先點擊按鈕觸發事件,調用接口去後臺請求下載的文件,然後後臺會以二進制流的方式把文件傳到你這裏,這裏可能需要一點時間,你可以加個loading的動畫,比如這樣:

2.對於拿到的文件流,前端會將其轉化爲blob,並加上保存的分類:

const blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;'});

[data]就是你獲取到的二進制流,後面的type就是你需要保存的文件格式,我這裏需要保存的是excel的文件 所以上面的類型是xlsx的格式類型;這樣一個文件格式是xlsx的blob;

3.對於一些現代瀏覽器,我們直接可以通過window.URL.createObjectURL方法處理blob,在dom裏面創建一個a標籤,js模擬點擊下載,最後在將創建的a標籤刪除,

const url = window.URL.createObjectURL(blob);
let link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', title);   //文件的保存名稱
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

這樣就完成了在現代瀏覽器的下載文件,但是對於一些高版本的IE就會出問題

比如這樣的錯誤

我們可以通過判斷IE瀏覽器然後以本地保存的方式;

 const ie = navigator.userAgent.match(/MSIE\s([\d.]+)/),
            ie11 = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/),
            ieEDGE = navigator.userAgent.match(/Edge/g),
            ieVer = (ie ? ie[1] : (ie11 ? 11 : (ieEDGE ? 12 : -1)));
         if (ie && ieVer < 10) {
            this.message.error('No blobs on IE<10');
            return;
        }
        if (ieVer > -1) {
            window.navigator.msSaveBlob(blob, title);
        }

 

完整代碼

downloadFile(title, data: Response) {
        const blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;'});

        const ie = navigator.userAgent.match(/MSIE\s([\d.]+)/),
            ie11 = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/),
            ieEDGE = navigator.userAgent.match(/Edge/g),
            ieVer = (ie ? ie[1] : (ie11 ? 11 : (ieEDGE ? 12 : -1)));
        console.log('ie:' + ie);
        console.log('ieVer:' + ieVer);
        if (ie && ieVer < 10) {
            this.message.error('No blobs on IE<10');
            return;
        }
        if (ieVer > -1) {
            window.navigator.msSaveBlob(blob, title);
        } else {
            const url = window.URL.createObjectURL(blob);
            let link = document.createElement('a');
            link.setAttribute('href', url);
            link.setAttribute('download', title);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }

 

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