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});
}