import axios from "axios"; import config from "@/app.config"; import { useCounterMixin } from "@/stores/mixin"; const mixin = useCounterMixin(); const { showLoader, hideLoader } = mixin; async function genReport(data: any, fileName: string, type: string = "docx") { showLoader(); await axios .post(config.API.reportTemplate + `/docx`, data, { headers: { "content-Type": "application/json", accept: type === "docx" ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document" : "application/pdf", }, responseType: "arraybuffer", }) .then((res) => { const responseData = res.data; if (responseData) { // --- ส่วนที่ปรับปรุง 1: กำหนด MIME Type ให้ตรงกับไฟล์ที่รับมาจริง --- const mimeType = type === "docx" ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document" : "application/pdf"; const blob = new Blob([responseData], { type: mimeType }); const url = URL.createObjectURL(blob); // --- ส่วนที่ปรับปรุง 2: จัดการชื่อไฟล์ (ป้องกันนามสกุลซ้อน) --- // ตัดช่องว่างหัวท้าย และตัดนามสกุลไฟล์เดิมที่อาจติดมาออก (.pdf, .docx ฯลฯ) const baseName = fileName.trim().replace(/\.[^/.]+$/, ""); const extension = type === "docx" ? "docx" : "pdf"; const link = document.createElement("a"); link.href = url; link.download = `${baseName}.${extension}`; // --- ส่วนที่ปรับปรุง 3: สำหรับ Android/Mobile --- // บางครั้งการ click() ทันทีอาจถูก block หรือมีปัญหา ต้อง append เข้าไปจริงๆ document.body.appendChild(link); link.click(); // หน่วงเวลาเล็กน้อยก่อนลบ element และ revoke URL เพื่อให้ Browser ทำงานเสร็จ setTimeout(() => { document.body.removeChild(link); URL.revokeObjectURL(url); }, 100); } }) .catch((err) => { console.log(err); }) .finally(() => { hideLoader(); }); } export default genReport;