下载方案,网上有很多方法 转换为a 加入下载标识的方法,可惜大一点的文件来说的话是不适用的,tony推荐以下方案有效规避 href src 长度限制问题,别的不多讲了,直接看码
IMGS={//下载图片
download(imgData,name) {
this.downloadFile(name?name:'test', imgData);
},
//下载
downloadFile(fileName, content) {
let aLink = document.createElement('a');
let blob = this.base64ToBlob(content); //new Blob([content]);
let evt = document.createEvent("HTMLEvents");
evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错 事件类型,是否冒泡,是否阻止浏览器的默认行为
aLink.download = fileName;
aLink.href = URL.createObjectURL(blob);
// aLink.dispatchEvent(evt);
aLink.click()
},
//base64转blob
base64ToBlob(code) {
let parts = code.split(';base64,');
let contentType = parts[0].split(':')[1];
let raw = window.atob(parts[1]);
let rawLength = raw.length;
let uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
},
};
以上方法重点在哪呢? base64ToBlob 没有错,以下是执行例子
IMGS.download('data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==','下载');
谢谢老哥!照搬拿去用,确实有效!