Chrome base64 轉換成檔案
下方是使用 JavaScript 把 base64 轉換成檔案的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| function downloadFile(base64Str) { const byteCharacters = atob(base64Str);
const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {type: 'image/jpg'}); let link = document.createElement('a'); const blobUrl = URL.createObjectURL(blob); link.href = blobUrl; link.download = 'file.jpg'; link.click(); URL.revokeObjectURL(blobUrl); }
|
IE 10 base64 轉換成檔案
如果瀏覽器使用 IE 10 以上版本,可使用 window.navigator.msSaveBlob 作為替代方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function downloadFile(base64Str) { const byteCharacters = atob(base64Str); const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {type: 'image/jpg'}); window.navigator.msSaveBlob(blob, 'file.jpg'); };
|