UNPKG

iking-utils-pro

Version:

金合前端工具库

2 lines (1 loc) 7.84 kB
function e(e){const t=e.split(","),o=t[0].match(/:(.*?);/)[1],n=atob(t[1]);let r=n.length;const i=new Uint8Array(r);for(;r--;)i[r]=n.charCodeAt(r);return new Blob([i],{type:o})}function t(e,t){return new Promise(((o,n)=>{let r=document.createElement("CANVAS");const i=r.getContext("2d"),d=new Image;d.crossOrigin="",d.onload=function(){if(!r||!i)return n();r.height=d.height,r.width=d.width,i.drawImage(d,0,0);const e=r.toDataURL(t||"image/png");r=null,o(e)},d.src=e}))}function o(e,o,r,i){t(e).then((e=>{n(e,o,r,i)}))}function n(t,o,n,i){r(e(t),o,n,i)}function r(e,t,o,n){const r=new Blob(void 0!==n?[n,e]:[e],{type:o||"application/octet-stream"}),i=window.URL.createObjectURL(r),d=document.createElement("a");d.style.display="none",d.href=i,d.setAttribute("download",t),void 0===d.download&&d.setAttribute("target","_blank"),document.body.appendChild(d),d.click(),document.body.removeChild(d),window.URL.revokeObjectURL(i)}function i({url:e,target:t="_blank",fileName:o}){if(window?.navigator){const n=window.navigator.userAgent.toLowerCase().indexOf("chrome")>-1,r=window.navigator.userAgent.toLowerCase().indexOf("safari")>-1;if(/(iP)/g.test(window.navigator.userAgent))return console.error("Your browser does not support download!"),!1;if(n||r){const n=document.createElement("a");if(n.href=e,n.target=t,void 0!==n.download&&(n.download=o||e.substring(e.lastIndexOf("/")+1,e.length)),document.createEvent){const e=document.createEvent("MouseEvents");return e.initEvent("click",!0,!0),n.dispatchEvent(e),!0}}return-1===e.indexOf("?")&&(e+="?download"),function(e,t){if("string"!=typeof e)return void console.error("openWindow: url必须是字符串");const{target:o="_blank",noopener:n=!0,noreferrer:r=!0}=t||{},i=[];n&&i.push("noopener=yes"),r&&i.push("noreferrer=yes"),window.open(e,o,i.join(","))}(e,{target:t}),!0}console.warn("小程序不支持此方法(downloadByUrl)")}const d=async(e,t,o)=>{const n=e;try{const e=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,__TYPE__:"DOWNLOAD"})});if(!e.ok)throw new Error(`HTTP error! status: ${e.status}`);const r=await e.blob(),i=e.headers.get("content-disposition"),d=/filename=([^;]+\.[^\.;]+)*/.exec(i||""),a=d?d[1]:o,s=document.createElement("a"),c=window.URL.createObjectURL(r);return s.style.display="none",s.href=c,s.download=decodeURI(a),document.body.appendChild(s),s.click(),document.body.removeChild(s),window.URL.revokeObjectURL(c),e}catch(e){console.info("ERROR",e)}},a=(e,t)=>{if(!e||"string"!=typeof e)return void console.error("downloadFile: url参数必须是有效的字符串");if(!t||"string"!=typeof t)return void console.error("downloadFile: fileName参数必须是有效的字符串");const o=new window.XMLHttpRequest;o.open("GET",e,!0),o.responseType="blob",o.onerror=()=>{console.error("下载文件时发生网络错误")},o.onload=()=>{if(200===o.status)try{const e=window.URL.createObjectURL(o.response),n=document.createElement("a");n.href=e,n.download=t,n.style.display="none",document.body.appendChild(n),n.click(),document.body.removeChild(n),window.URL.revokeObjectURL(e)}catch(e){console.error("处理下载文件时发生错误:",e)}else console.error(`下载文件失败,状态码: ${o.status}`)},o.send()};let s="object"==typeof window&&window.window===window?window:"object"==typeof self&&self.self===self?self:"object"==typeof globalThis&&globalThis.globalThis===globalThis?globalThis:void 0;function c(e,t,o){const n=new XMLHttpRequest;n.open("GET",e),n.responseType="blob",n.onload=function(){u(n.response,t,o)},n.onerror=function(){console.error("could not download file")},n.send()}function l(e){const t=new XMLHttpRequest;t.open("HEAD",e,!1);try{t.send()}catch(e){}return t.status>=200&&t.status<=299}function p(e){try{e.dispatchEvent(new MouseEvent("click"))}catch(t){const o=document.createEvent("MouseEvents");o.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),e.dispatchEvent(o)}}const w=s?.navigator&&/Macintosh/.test(navigator?.userAgent)&&/AppleWebKit/.test(navigator?.userAgent)&&!/Safari/.test(navigator?.userAgent),u=(e,t,o,n)=>{if("download"in HTMLAnchorElement.prototype&&!w){const n=s.URL||s.webkitURL,r=document.createElementNS("http://www.w3.org/1999/xhtml","a");t=t||e?.name||"download",r.download=t,r.rel="noopener","string"==typeof e?(r.href=e,r.origin!==location.origin?l(r.href)?c(e,t,o):(r.target="_blank")&&p(r):p(r)):(r.href=n.createObjectURL(e),setTimeout((function(){n.revokeObjectURL(r.href)}),4e4),setTimeout((function(){p(r)}),0))}else if(navigator?.msSaveOrOpenBlob)if(t=t||e.name||"download","string"==typeof e)if(l(e))c(e,t,o);else{var r=document.createElement("a");r.href=e,r.target="_blank",setTimeout((function(){p(r)}))}else navigator?.msSaveOrOpenBlob(function(e,t){return void 0===t?t={autoBom:!1}:"object"!=typeof t&&(console.warn("第二个参数类型必须是object"),t={autoBom:!t}),t.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e?.type)?new Blob([String.fromCharCode(65279),e],{type:e?.type}):e}(e,o),t);else{if((n=n||open("","_blank"))&&(n.document.title=n.document.body.innerText="downloading..."),"string"==typeof e)return c(e,t,o);const r="application/octet-stream"===e.type,i=/constructor/i.test(s.HTMLElement)||s.safari,d=/CriOS\/[\d]+/.test(navigator?.userAgent);if((d||r&&i||w)&&"undefined"!=typeof FileReader){const t=new FileReader;t.onloadend=function(){let e=t.result;e=d?e:e?.replace(/^data:[^;]*;/,"data:attachment/file;"),n?n.location.href=e:location.href=e,n=null},t.readAsDataURL(e)}else{const t=s.URL||s.webkitURL,o=t.createObjectURL(e);n?n.location=o:location.href=o,n=null,setTimeout((function(){t.revokeObjectURL(o)}),4e4)}}},f=(e,t)=>{const o=e?.response?.data?g(e?.response?.data?.suffix):e.raw?.type||g(e[t.suffix]),n=o?.toLowerCase(),r={sheet:"excel",excel:"excel",zip:"zip","application/x-compressed":"zip",image:"image",video:"video",audio:"audio",pdf:"pdf",text:"txt",txt:"txt",word:"word",ppt:"ppt",exe:"exe",json:"json"};for(let e in r)if("string"==typeof n&&(n.includes(e)||n===e))return r[e];return"unknown"},m={".doc":"word",".docx":"word",".docxf":"word",".docm":"word",".dot":"word",".dotm":"word",".dotx":"word",".epub":"word",".fodt":"word",".htm":"word",".html":"word",".mht":"word",".odt":"word",".ott":"word",".rtf":"word",".djvu":"word",".oxps":"word",".oform":"word",".fb2":"word",".xml":"word",".xps":"word",".csv":"excel",".xls":"excel",".xlsx":"excel",".fods":"excel",".ods":"excel",".ots":"excel",".xlsb":"excel",".xlsm":"excel",".xlt":"excel",".xltm":"excel",".xltx":"excel",".fodp":"ppt",".odp":"ppt",".otp":"ppt",".pot":"ppt",".potm":"ppt",".potx":"ppt",".pps":"ppt",".ppsm":"ppt",".ppsx":"ppt",".ppt":"ppt",".pptm":"ppt",".pptx":"ppt",".zip":"zip",".rar":"zip",".7z":"zip",".apz":"zip",".ar":"zip",".bz":"zip",".car":"zip",".dar":"zip",".cpgz":"zip",".f":"zip",".ha":"zip",".hbc":"zip",".hbc2":"zip",".hbe":"zip",".hpk":"zip",".hyp":"zip",".png":"image",".jpg":"image",".jpeg":"image",".bmp":"image",".gif":"image",".webp":"image",".psd":"image",".svg":"image",".tiff":"image",".avi":"video",".wmv":"video",".mpeg":"video",".mp4":"video",".mpm4v":"video",".mov":"video",".asf":"video",".flv":"video",".f4v":"video",".rmvb":"video",".rm":"video",".3gp":"video",".vob":"video",".txt":"txt",".pdf":"pdf"},g=e=>{const t=e?.toLocaleLowerCase(),o=t?.startsWith(".")?t:`.${t}`;return o&&m[o]||"unknow"},h=e=>{let t="";return["doc","docx"].includes(e)&&(t="word"),["xls","xlsx"].includes(e)&&(t="cell"),["ppt","pptx"].includes(e)&&(t="slide"),["pdf"].includes(e)&&(t="text-pdf"),t};export{e as base64ToBlob,n as downloadByBase64,r as downloadByData,o as downloadByOnlineUrl,i as downloadByUrl,a as downloadFile,d as fetchFileAndDownload,g as getFileAttr,f as getFileType,h as getFileTypes,w as isMacOSWebView,u as saveAs,t as urlToBase64};