|
| 1 | +import { CustomHeaders } from 'uiSrc/constants/api' |
| 2 | + |
1 | 3 | /** |
2 | | - * Triggers a file download from a URL by creating a temporary link element |
| 4 | + * Triggers a file download from a URL using fetch with proper headers |
| 5 | + * This is necessary for Electron app where window ID authentication is required |
3 | 6 | * @param url The full URL to download from |
4 | 7 | */ |
5 | | -export const triggerDownloadFromUrl = (url: string): void => { |
| 8 | +export const triggerDownloadFromUrl = async (url: string): Promise<void> => { |
| 9 | + const headers: Record<string, string> = {} |
| 10 | + |
| 11 | + // Add window ID header for Electron app authentication |
| 12 | + if (window.windowId) { |
| 13 | + headers[CustomHeaders.WindowId] = window.windowId |
| 14 | + } |
| 15 | + |
| 16 | + const response = await fetch(url, { headers }) |
| 17 | + |
| 18 | + if (!response.ok) { |
| 19 | + throw new Error(`Download failed: ${response.statusText}`) |
| 20 | + } |
| 21 | + |
| 22 | + // Extract filename from Content-Disposition header |
| 23 | + const contentDisposition = response.headers.get('content-disposition') || '' |
| 24 | + const filenameMatch = contentDisposition.match(/filename="?([^";\n]+)"?/) |
| 25 | + const filename = filenameMatch?.[1] || 'download' |
| 26 | + |
| 27 | + // Convert response to blob and trigger download |
| 28 | + const blob = await response.blob() |
| 29 | + const blobUrl = URL.createObjectURL(blob) |
| 30 | + |
6 | 31 | const link = document.createElement('a') |
7 | | - link.href = url |
| 32 | + link.href = blobUrl |
| 33 | + link.download = filename |
8 | 34 | link.style.display = 'none' |
9 | 35 | document.body.appendChild(link) |
10 | 36 | link.click() |
11 | 37 | document.body.removeChild(link) |
| 38 | + |
| 39 | + // Clean up the blob URL |
| 40 | + URL.revokeObjectURL(blobUrl) |
12 | 41 | } |
0 commit comments