import { useUserStore } from '../store/user/userStore'; /** * Download a file from the API as a blob and trigger a browser download. * * @param endpoint - API path (e.g. '/rooms/template') * @param filename - Suggested filename for the download */ export async function downloadBlob(endpoint: string, filename: string): Promise { const baseURL = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`; const token = useUserStore.getState().token; const res = await fetch(`${baseURL}${endpoint}`, { headers: { Authorization: `Bearer ${token}` }, }); if (!res.ok) { const text = await res.text().catch(() => ''); throw new Error(text || `下载失败 (HTTP ${res.status})`); } const blob = await res.blob(); 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); }