forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdownload.ts
More file actions
41 lines (38 loc) · 1.29 KB
/
Copy pathdownload.ts
File metadata and controls
41 lines (38 loc) · 1.29 KB
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
32
33
34
35
36
37
38
39
40
41
// src/lib/download.ts
//
// Functions: extractFilename, triggerBlobDownload, downloadResponseBlob
/**
* Extracts a filename from a Content-Disposition header.
* Falls back to the provided default if the header is missing or unparseable.
*/
export function extractFilename(response: Response, fallback: string): string {
const disposition = response.headers.get("Content-Disposition") ?? ""
const match = disposition.match(/filename="?([^"]+)"?/)
return match?.[1] ?? fallback
}
/**
* Triggers a browser file download from a Blob.
* Creates a temporary anchor element, clicks it, and cleans up.
*/
export function triggerBlobDownload(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
}
/**
* Convenience: extracts blob + filename from a Response, then triggers download.
* Combines extractFilename + triggerBlobDownload for the common case.
*/
export async function downloadResponseBlob(
response: Response,
fallbackFilename: string
): Promise<void> {
const blob = await response.blob()
const filename = extractFilename(response, fallbackFilename)
triggerBlobDownload(blob, filename)
}