|
| 1 | +export type FileContent = string | ArrayBuffer; |
| 2 | + |
| 3 | +export enum FileType { |
| 4 | + JSON = "json", |
| 5 | + PDF = "pdf", |
| 6 | + SpreadSheet = "xlsx", |
| 7 | + XML = "xml", |
| 8 | +} |
| 9 | + |
| 10 | +export function downloadFile( |
| 11 | + content: FileContent, |
| 12 | + fileName: string, |
| 13 | + type: FileType |
| 14 | +) { |
| 15 | + const blob: Blob = toBlob(content, type); |
| 16 | + save(blob, fileName); |
| 17 | +} |
| 18 | + |
| 19 | +function toBlob(content: FileContent, type: FileType): Blob { |
| 20 | + const byteArray: Array<ArrayBuffer | Uint8Array> = |
| 21 | + typeof content === "string" ? toByteArray(content) : [content]; |
| 22 | + return new Blob(byteArray, { type: toContentType(type) }); |
| 23 | +} |
| 24 | + |
| 25 | +function toByteArray( |
| 26 | + base64Data: string, |
| 27 | + sliceSize: number = 512 |
| 28 | +): Array<Uint8Array> { |
| 29 | + const byteCharacters: string = window.atob(base64Data); |
| 30 | + const byteArrays: Array<Uint8Array> = []; |
| 31 | + |
| 32 | + for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { |
| 33 | + const slice: string = byteCharacters.slice(offset, offset + sliceSize); |
| 34 | + const byteNumbers: Array<number> = new Array(slice.length); |
| 35 | + |
| 36 | + for (let i = 0; i < slice.length; i++) { |
| 37 | + byteNumbers[i] = slice.charCodeAt(i); |
| 38 | + } |
| 39 | + |
| 40 | + byteArrays.push(new Uint8Array(byteNumbers)); |
| 41 | + } |
| 42 | + |
| 43 | + return byteArrays; |
| 44 | +} |
| 45 | + |
| 46 | +function toContentType(type: FileType): string { |
| 47 | + switch (type) { |
| 48 | + case FileType.PDF: |
| 49 | + return "application/pdf"; |
| 50 | + |
| 51 | + case FileType.SpreadSheet: |
| 52 | + return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; |
| 53 | + |
| 54 | + case FileType.JSON: |
| 55 | + return "application/json"; |
| 56 | + |
| 57 | + case FileType.XML: |
| 58 | + return "text/xml"; |
| 59 | + |
| 60 | + default: |
| 61 | + return "text/plain"; |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +function save(blob: Blob, fileName: string): void { |
| 66 | + const url: string = window.URL.createObjectURL(blob); |
| 67 | + const downloadableLink: HTMLAnchorElement = document.createElement("a"); |
| 68 | + downloadableLink.download = fileName; |
| 69 | + downloadableLink.href = url; |
| 70 | + downloadableLink.style.display = "none"; |
| 71 | + document.body.appendChild(downloadableLink); |
| 72 | + downloadableLink.click(); |
| 73 | + downloadableLink.remove(); |
| 74 | + window.URL.revokeObjectURL(url); |
| 75 | +} |
0 commit comments