浏览器下载img标签Base64图片
程序员文章站
2022-08-09 22:34:06
https://blog.csdn.net/qq_42076140/article/details/82113622 原文地址 ......
https://blog.csdn.net/qq_42076140/article/details/82113622 原文地址
<a href="javascript:download();" >点击下载图片</a>
//下载图片
function download() {
var imgdata = $("#showpaypic").prop('src');//这里放需要下载的base64
downloadfile(new date().gettime()+".png", imgdata);
}
//下载
function downloadfile(filename, content) {
var alink = document.createelement('a');
var blob = this.base64toblob(content); //new blob([content]);
var 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
function base64toblob(code) {
var parts = code.split(';base64,');
var contenttype = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawlength = raw.length;
var uint8array = new uint8array(rawlength);
for (var i = 0; i < rawlength; ++i) {
uint8array[i] = raw.charcodeat(i);
}
return new blob([uint8array], {type: contenttype});
}
下一篇: ES6迭代器