在项目开发过程中,经常会有图片导出的需求,而图片格式是base64编码。
function downloadFile(base64, fileName) {
let base64ToBlob = function(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
});
};
let aLink = document.createElement('a');
let blob = base64ToBlob(base64);
let evt = document.createEvent("htmlEvents");
evt.initEvent("click", true, true);
aLink.download = fileName;
aLink.href = URL.createObjectURL(blob);
aLink.click();
};
1、首先创建a标签
2、将base64转为blob对象
3、利用a标签的特性,通过URL.createObjectURL方法赋值给href,通过点击事件实现下载
注意:initEvent不加后两个参数在FF下会报错,事件类型,是否冒泡,是否阻止浏览器的默认行为