UNPKG

@ryanuo/utils

Version:

提供多种实用工具函数,涵盖算法、浏览器操作、网络请求等多个领域

34 lines (33 loc) 1.44 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.downloadFile = downloadFile; async function downloadFile(url, fileName, options = {}) { try { const response = await fetch(url, options); if (!response.ok) throw new Error(`\u4E0B\u8F7D\u5931\u8D25: HTTP\u72B6\u6001\u7801 ${response.status} ${response.statusText}`); if (!fileName) { const contentDisposition = response.headers.get("content-disposition"); if (contentDisposition) { const fileNameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/); if (fileNameMatch && fileNameMatch[1]) fileName = fileNameMatch[1].replace(/['"]/g, ""); } if (!fileName) fileName = url.split("/").pop() || "downloaded-file"; } const blob = await response.blob(); const downloadUrl = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = downloadUrl; link.download = fileName; document.body.appendChild(link); link.click(); setTimeout(() => { document.body.removeChild(link); URL.revokeObjectURL(downloadUrl); }, 100); } catch (error) { console.error("\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25:", error); if (error instanceof Error) throw new Error(`\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25: ${error.message}`);else throw new Error("\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25: \u53D1\u751F\u672A\u77E5\u9519\u8BEF"); } }