JS-下載附件downloadjs源碼分析

最近在一個項(xiàng)目中碰到了下載附件的需求,自己擼了一下,效果不是很理想,文件類型,以及瀏覽器的兼容性,這方面處理的不是很好,于是尋找?guī)椭业搅艘粋€downloadjs的npm包,然后自己分析源碼,嘿嘿,以后就直接用了
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], factory);
    } else if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        root.download = factory();
  }
}(this, function () {
//data表示要下載的數(shù)據(jù),strFileName表示文件名,strMimeType表示文件的mineType
    return function download(data, strFileName, strMimeType) {}
})

可以看到最后輸出的實(shí)際是download的這個方法,可以直接使用,繼續(xù)看

payload = data,
url = !strFileName && !strMimeType && payload
if(url && url.length< 2048){ 
            fileName = url.split("/").pop().split("?")[0];
            anchor.href = url; // assign href prop to temp anchor
            if(anchor.href.indexOf(url) !== -1){ // if the browser determines that it's a potentially valid url path:
                var ajax=new XMLHttpRequest();
                ajax.open( "GET", url, true);
                ajax.responseType = 'blob';
                ajax.onload= function(e){ 
                  download(e.target.response, fileName, defaultMime);
                };
                setTimeout(function(){ ajax.send();}, 0); // allows setting custom ajax headers using the return:
                return ajax;
            } // end if valid url?
} // end if url?

如果strFileName,strMimeType兩個參數(shù)不傳的話,參數(shù)形式就是url的形式,這個時(shí)候
會發(fā)送一個請求,得到這個url的二進(jìn)制流,然后繼續(xù)調(diào)我們download方法(阿西吧,這次才是正真正的調(diào)用),繼續(xù)看

if(/^data:([\w+-]+\/[\w+.-]+)?[,;]/.test(payload)){
          // 如果是二進(jìn)制格式的數(shù)據(jù)流,將其轉(zhuǎn)換成二進(jìn)制的對象
            if(payload.length > (1024*1024*1.999) && myBlob !== toString ){
                payload=dataUrlToBlob(payload);
                mimeType=payload.type || defaultMime;
            }else{  
                               // 如果瀏覽器支持的話,就直接下載,不支持的話,就我們自己寫方法        
                return navigator.msSaveBlob ?  // IE10 can't do a[download], only Blobs:
                    navigator.msSaveBlob(dataUrlToBlob(payload), fileName) :
                    saver(payload) ; // everyone else can save dataURLs un-processed
            }

將二進(jìn)制流轉(zhuǎn)換成二進(jìn)制對象,繼續(xù)看

function saver(url, winMode){

            if ('download' in anchor) { //html5 A[download]
                anchor.href = url;
                anchor.setAttribute("download", fileName);
                anchor.className = "download-js-link";
                anchor.innerHTML = "downloading...";
                anchor.style.display = "none";
                document.body.appendChild(anchor);
                setTimeout(function() {
                    anchor.click();
                    document.body.removeChild(anchor);
                    if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(anchor.href);}, 250 );}
                }, 66);
                return true;
            }

            // handle non-a[download] safari as best we can:
            if(/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
                if(/^data:/.test(url))  url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
                if(!window.open(url)){ // popup blocked, offer direct download:
                    if(confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")){ location.href=url; }
                }
                return true;
            }

            //do iframe dataURL download (old ch+FF):
            var f = document.createElement("iframe");
            document.body.appendChild(f);

            if(!winMode && /^data:/.test(url)){ // force a mime that will download:
                url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
            }
            f.src=url;
            setTimeout(function(){ document.body.removeChild(f); }, 333);

        }

如果支持H5的download,就使用h5的方式,不然的話使用iframe的方式

總結(jié)下來就兩步,第一步將需要下載的數(shù)據(jù)轉(zhuǎn)換成二進(jìn)制對象,第二步,將二進(jìn)制的對象下載

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,645評論 19 139
  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 7,361評論 0 17
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,176評論 25 708
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,740評論 18 399
  • 文/井底女蛙 時(shí)代不同了,觀點(diǎn)更新太快,看過很多關(guān)于離婚的熱門文章,發(fā)現(xiàn)越來越多的人支持“不要為了孩子,委屈自己,...
    井底女蛙閱讀 3,946評論 92 129

友情鏈接更多精彩內(nèi)容