Files
Artveris/apps/admin/src/utils/download.ts
T

29 lines
948 B
TypeScript

import { download } from '@/api/request';
export function saveBlob(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);
}
export async function downloadFile(url: string, filename: string, params?: object): Promise<void> {
const res = await download(url, params);
saveBlob(res.data, pickFilename(res.headers, filename));
}
function pickFilename(headers: Record<string, string>, fallback: string): string {
const disposition = headers['content-disposition'] || headers['Content-Disposition'];
const match = disposition?.match(/filename\*?=(?:UTF-8''|")?([^";]+)/i);
if (!match?.[1]) return fallback;
try {
return decodeURIComponent(match[1].replace(/"/g, ''));
} catch {
return match[1].replace(/"/g, '');
}
}