downloadjs github地址
判断环境
(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 () {
//...
}
初始化
(function (root, factory) {
//...
}(this, function () {
return function download(data, strFileName, strMimeType) {
var self = window, // this script is only for browsers anyway...
defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
mimeType = strMimeType || defaultMime,
payload = data,
// 只传第一个参数,说明通过url下载,否则是下载指定内容
url = !strFileName && !strMimeType && payload,
// 默认通过a标签进行下载
anchor = document.createElement("a"),
toString = function(a){return String(a);},
// 默认将下载内容转换成blob
myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
fileName = strFileName || "download",
blob,
reader;
myBlob= myBlob.call ? myBlob.bind(self) : Blob ;
}
if(String(this)==="true"){ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
payload=[payload, mimeType];
mimeType=payload[0];
payload=payload[1];
}
//...
})
统一的下载方法
function saver(url, winMode){
// 默认通过a标签的 download 进行下载
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);
// 浏览器window环境 URL.revokeObjectURL 释放资源
if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(anchor.href);}, 250 );}
}, 66);
return true;
}
// 如果不支持a标签下载,通过location.href下载,但只能下载.rar、.exe这种浏览器无法直接打开的包,否则浏览器将直接打开文件
// handle non-a[download] safari as best we can:
if(/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
// data url的格式统一改成'application/octet-stream',表示浏览器不用知道是什么类型,只知道是二进制文件,触发下载行为
if(/^data:/.test(url)) url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
//window.open不行就使用confirm打开页面下载
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;
}
// 老版本谷歌+火狐通过iframe下载
//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);
}//end saver
下载给定内容
(function (root, factory) {
//...
}(this, function () {
return function download(data, strFileName, strMimeType) {
// ...
//将传递的data转换成blob格式,以及判断传递的data是否已经是blob
blob = payload instanceof myBlob ?
payload :
new myBlob([payload], {type: mimeType}) ;
//兼容ie10+
if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
return navigator.msSaveBlob(blob, fileName);
}
// 将blob转化成blob url
if(self.URL){ // simple fast and modern way using Blob and URL:
// 将blob data内容变成blob url
saver(self.URL.createObjectURL(blob), true);
}else{
// handle non-Blob()+non-URL browsers:
// 如果不支持winodw.Blob,手动转换成base64格式
if(typeof blob === "string" || blob.constructor===toString ){
try{
return saver( "data:" + mimeType + ";base64," + self.btoa(blob) );
}catch(y){
return saver( "data:" + mimeType + "," + encodeURIComponent(blob) );
}
}
// 支持blob但是不支持window.URL,通过FileReader转换成Blob url
// Blob but not URL support:
reader=new FileReader();
reader.onload=function(e){
saver(this.result);
};
reader.readAsDataURL(blob);
}
return true
}
}));
(function (root, factory) {
//...
}(this, function () {
return function download(data, strFileName, strMimeType) {
// ...
// 当传入的是base64
//go ahead and download dataURLs right away
if(/^data:([\w+-]+\/[\w+.-]+)?[,;]/.test(payload)){
if(payload.length > (1024*1024*1.999) && myBlob !== toString ){
// 转换成blob
payload=dataUrlToBlob(payload);
mimeType=payload.type || defaultMime;
}else{
// 兼容ie10
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
}
}else{//not data url, is it a string with special needs?
// 匹配中文字符等特殊字符,这里判定成特殊字符串,即下载内容是该字符串
if(/([\x80-\xff])/.test(payload)){
var i=0, tempUiArr= new Uint8Array(payload.length), mx=tempUiArr.length;
for(i;i<mx;++i) tempUiArr[i]= payload.charCodeAt(i);
payload=new myBlob([tempUiArr], {type: mimeType});
}
}
function dataUrlToBlob(strUrl) {
// 这里使用正则split
var parts= strUrl.split(/[:;,]/),
//'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAMAAAAOusbgAAAAeFBMVEUAwAD///+U5ZTc9twOww7G8MYwzDCH4=='.split(/[:;,]/)
//['data', 'image/png', 'base64', 'iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAMAAAAOusbgAAAAeFBMVEUAwAD///+U5ZTc9twOww7G8MYwzDCH4==']
type= parts[1],
// base64使用atob进行解码
decoder= parts[2] == "base64" ? atob : decodeURIComponent,
binData= decoder( parts.pop() ),
mx= binData.length,
i= 0,
uiArr= new Uint8Array(mx);
for(i;i<mx;++i) uiArr[i]= binData.charCodeAt(i);
return new myBlob([uiArr], {type: type});
}
// 接下来的流程和下载字符串一致
blob = payload instanceof myBlob ?
payload :
new myBlob([payload], {type: mimeType}) ;
}
})
(function (root, factory) {
//...
}(this, function () {
return function download(data, strFileName, strMimeType) {
// ...
//将传递的data转换成blob格式,以及判断传递的data是否已经是blob
blob = payload instanceof myBlob ?
payload :
new myBlob([payload], {type: mimeType}) ;
//接下来和字符串转换成blob格式后下载一致
//...
}
})
通过url下载
(function (root, factory) {
//...
}(this, function () {
return function download(data, strFileName, strMimeType) {
//...
// 如果第一参数传递的是url
if(url && url.length< 2048){ // if no filename and no mime, assume a url was passed as the only argument
fileName = url.split("/").pop().split("?")[0];
anchor.href = url; // assign href prop to temp anchor
//通过浏览器标签去校验是否url是否合法,骚操作
if(anchor.href.indexOf(url) !== -1){ // if the browser determines that it's a potentially valid url path:
//通过ajax发起下载请求,返回blob二进制流
var ajax=new XMLHttpRequest();
ajax.open( "GET", url, true);
ajax.responseType = 'blob';
ajax.onload= function(e){
//此时传入的是二进制,递归调用download,走下载二进制流的逻辑
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?
}
})