最近在一個項(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)制的對象下載