js下載base64格式的圖片(相容火狐)
阿新 • • 發佈:2018-12-20
//下載圖片 download() { let imgData = 'data:image/png;base64,iVBORw0KGgoAAAANSUh........'; this.downloadFile('測試.png', 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() aLink.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));//相容火狐 }, //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}); }