blob: c3e98b0c82ce2d622fdbd52dbcfc05565292d054 (
plain) (
blame)
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
|
// Yoinked from https://web.dev/patterns/files/save-a-file/ for the polyfill
export default async function saveFile(blob: ArrayBuffer, suggestedName: string | undefined) {
const supportsFSAccess =
'showSaveFilePicker' in window &&
(() => {
try {
return window.self === window.top;
} catch {
return false;
}
})();
if (supportsFSAccess) {
try {
const handle = await window.showSaveFilePicker({
suggestedName: suggestedName
});
const writable = await handle.createWritable();
await writable.write(blob);
await writable.close();
return;
} catch (err: unknown) {
// TypeScript
if ((err as Error)?.name !== 'AbortError') {
return Promise.reject(err);
}
}
} else {
const anchor = document.createElement('a');
anchor.download = suggestedName ?? 'truncated';
anchor.href = URL.createObjectURL(new Blob([blob]));
anchor.click();
URL.revokeObjectURL(anchor.href);
document.body.removeChild(anchor);
}
}
|