/** * ดาวน์โหลดไฟล์จากคำตอบของ API ฝั่ง client — แทน fetch → blob → createObjectURL → อ่านชื่อไฟล์เอง * (supplychain เขียนแบบนี้เอง 6 จุด) * * const res = await fetch(`/api/vendors/export?format=xlsx`); * await downloadResponse(res, "vendors.xlsx"); // ชื่อจาก Content-Disposition ก่อน แล้วค่อย fallback */ /** ชื่อไฟล์จาก header `Content-Disposition` — รองรับ `filename*=UTF-8''…` (ชื่อไทย) และ `filename="…"` */ export function fileNameFromContentDisposition(header: string | null | undefined): string | null { if (!header) return null; const star = /filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(header); if (star?.[1]) { try { return decodeURIComponent(star[1].trim().replace(/^"|"$/g, "")); } catch { // ชื่อเข้ารหัสผิด → ลอง filename= ธรรมดาต่อ } } const plain = /filename\s*=\s*("([^"]*)"|[^;]+)/.exec(header); const name = plain?.[2] ?? plain?.[1]; return name ? name.trim() : null; } /** บันทึก Blob เป็นไฟล์ (ลิงก์ชั่วคราว + คืน URL หลังคลิก) */ export function downloadBlob(blob: Blob, fileName: string): void { const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = fileName; link.rel = "noopener"; link.style.display = "none"; document.body.appendChild(link); link.click(); link.remove(); // Safari ยกเลิกการดาวน์โหลดถ้าคืน URL ทันที setTimeout(() => URL.revokeObjectURL(url), 1000); } /** * ดาวน์โหลดจาก `Response` — ไม่ ok = throw (ข้อความจาก body ถ้าเป็นข้อความสั้น ๆ) · คืนชื่อไฟล์ที่ใช้ * ชื่อ: `Content-Disposition` → `fallbackName` → ส่วนท้ายของ URL → "download" */ export async function downloadResponse(response: Response, fallbackName?: string): Promise { if (!response.ok) { const body = await response.text().catch(() => ""); const message = body && body.length <= 300 && !body.trimStart().startsWith("<") ? body : ""; throw new Error(message || `HTTP ${response.status}`); } const fromUrl = (() => { try { const last = new URL(response.url).pathname.split("/").pop(); return last?.includes(".") ? decodeURIComponent(last) : null; } catch { return null; } })(); const fileName = fileNameFromContentDisposition(response.headers.get("content-disposition")) ?? fallbackName ?? fromUrl ?? "download"; downloadBlob(await response.blob(), fileName); return fileName; }