UNPKG

@aplus-frontend/utils

Version:

Utils for Aplus frontend team.

52 lines (51 loc) 1.91 kB
function downloadByData(data, filename, mime, bom) { var _a; const blobData = typeof bom !== "undefined" ? [bom, data] : [data]; const blob = new Blob(blobData, { type: mime || "application/octet-stream" }); const blobURL = window.URL.createObjectURL(blob); const tempLink = document.createElement("a"); tempLink.style.display = "none"; tempLink.href = blobURL; tempLink.setAttribute("download", filename); if (typeof tempLink.download === "undefined") { tempLink.setAttribute("target", "_blank"); } document.body.appendChild(tempLink); tempLink.click(); (_a = tempLink.parentElement) == null ? void 0 : _a.removeChild(tempLink); window.URL.revokeObjectURL(blobURL); } function formatHeadersFilesName(str = "") { let fileName = ""; const fileNameMatch = str == null ? void 0 : str.match( /attachment;filename\*=utf-8''(.+)|filename="?(.+?)"?($|;)/ ); if (fileNameMatch) { fileName = decodeURIComponent((fileNameMatch == null ? void 0 : fileNameMatch[1]) || (fileNameMatch == null ? void 0 : fileNameMatch[2])); } return fileName; } async function formatFileNameAndDownloadFile(request) { return new Promise((resolve, reject) => { var _a, _b, _c; if ((request == null ? void 0 : request.data) && request.headers && ((_a = request == null ? void 0 : request.headers) == null ? void 0 : _a["content-disposition"])) { downloadByData( request.data, formatHeadersFilesName(request.headers["content-disposition"]) ); resolve(true); } else { (_c = (_b = request == null ? void 0 : request.data) == null ? void 0 : _b.text()) == null ? void 0 : _c.then((str) => { const data = JSON.parse(str || "{}"); if (data.code && data.code !== "200") { reject(data.message); } }); } }); } export { downloadByData, formatFileNameAndDownloadFile, formatHeadersFilesName };