123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243 |
- const storagePrefix = "cet_";
- /**
- * LocalStorage
- */
- export const local = {
- set(table: string, settings: any) {
- const _set = JSON.stringify(settings);
- return localStorage.setItem(storagePrefix + table, _set);
- },
- get(table: string) {
- let data: any = localStorage.getItem(storagePrefix + table);
- try {
- data = JSON.parse(data);
- } catch (err) {
- return null;
- }
- return data;
- },
- remove(table: string) {
- return localStorage.removeItem(storagePrefix + table);
- },
- clear() {
- return localStorage.clear();
- },
- };
- /**
- * SessionStorage
- */
- export const session = {
- set(table: string, settings: any) {
- const _set = JSON.stringify(settings);
- return sessionStorage.setItem(storagePrefix + table, _set);
- },
- get(table: string) {
- let data: any = sessionStorage.getItem(storagePrefix + table);
- try {
- data = JSON.parse(data);
- } catch (err) {
- return null;
- }
- return data;
- },
- remove(table: string) {
- return sessionStorage.removeItem(storagePrefix + table);
- },
- clear() {
- return sessionStorage.clear();
- },
- };
- export const clearStorage = () => {
- localStorage.clear();
- sessionStorage.clear();
- };
- export const generateId = function () {
- return Math.floor(
- Math.random() * 100000 + Math.random() * 20000 + Math.random() * 5000
- );
- };
- /* 日期格式化 */
- export const dateFormat = (
- date: any,
- fmt = "yyyy/MM/dd HH:mm:ss",
- isDefault = "-"
- ) => {
- if (!date) {
- return "-";
- }
- if (date.toString().length === 10) {
- date *= 1000;
- }
- date = new Date(date);
- if (date.valueOf() < 1) {
- return isDefault;
- }
- const o: any = {
- "M+": date.getMonth() + 1, // 月份
- "d+": date.getDate(), // 日
- "H+": date.getHours(), // 小时
- "m+": date.getMinutes(), // 分
- "s+": date.getSeconds(), // 秒
- "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
- S: date.getMilliseconds(), // 毫秒
- };
- if (/(y+)/.test(fmt)) {
- fmt = fmt.replace(
- RegExp.$1,
- `${date.getFullYear()}`.substr(4 - RegExp.$1.length)
- );
- }
- for (const k in o) {
- if (new RegExp(`(${k})`).test(fmt)) {
- fmt = fmt.replace(
- RegExp.$1,
- RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length)
- );
- }
- }
- return fmt;
- };
- export const extractFileName = (str: string) => {
- if (/filename=([^;\s]*)/gi.test(str)) {
- return decodeURIComponent(RegExp.$1);
- }
- return "下载文件";
- };
- export const download = (res: any, downName = "") => {
- const aLink = document.createElement("a");
- let fileName = downName;
- let blob = res; // 第三方请求返回blob对象
- // 通过后端接口返回
- if (res.headers && res.data) {
- blob = new Blob([res.data], {
- type: res.headers["content-type"].replace(";charset=utf8", ""),
- });
- if (!downName) {
- fileName = extractFileName(res.headers?.["content-disposition"]);
- }
- }
- aLink.href = URL.createObjectURL(blob);
- // 设置下载文件名称
- aLink.setAttribute("download", fileName);
- document.body.appendChild(aLink);
- aLink.click();
- document.body.removeChild(aLink);
- URL.revokeObjectURL(aLink.href);
- };
- /**
- * 下载url
- * @param {String} url 文件下载地址
- * @param {String}} filename 文件名
- */
- export function downloadByUrl(url: string, filename: string) {
- const tempLink = document.createElement("a");
- tempLink.style.display = "none";
- tempLink.href = url;
- const fileName =
- filename || url.split("/").pop()?.split("?")[0] || "未命名文件";
- tempLink.setAttribute("download", fileName);
- if (tempLink.download === "undefined") {
- tempLink.setAttribute("target", "_blank");
- }
- document.body.appendChild(tempLink);
- tempLink.click();
- document.body.removeChild(tempLink);
- window.URL.revokeObjectURL(url);
- }
- export function urlToBlob(url: string, cb: Function) {
- const xhr = new XMLHttpRequest();
- xhr.open("GET", url, true);
- xhr.responseType = "blob";
- xhr.onload = function () {
- if (xhr.status == 200) {
- cb(URL.createObjectURL(xhr.response));
- }
- };
- xhr.send();
- }
- export function saveAs(blob: Blob, filename: string) {
- if ((window as any).navigator.msSaveOrOpenBlob) {
- (navigator as any).msSaveBlob(blob, filename);
- } else {
- var link: any = document.createElement("a");
- var body = document.querySelector("body") as HTMLBodyElement;
- link.href = blob;
- link.download = filename;
- link.style.display = "none";
- body.appendChild(link);
- link.click();
- body.removeChild(link);
- window.URL.revokeObjectURL(link.href);
- }
- }
- export function downloadByCrossUrl(url: string, filename: string) {
- urlToBlob(url, (blob: Blob) => {
- saveAs(blob, filename);
- });
- }
- export const getRequestParams = (url: string) => {
- const theRequest: any = new Object();
- if (url.indexOf("?") != -1) {
- const params = url.split("?")[1].split("&");
- for (let i = 0; i < params.length; i++) {
- const param = params[i].split("=");
- theRequest[param[0]] = decodeURIComponent(param[1]);
- }
- }
- return theRequest;
- };
- /**
- * 字典数据转成option list
- * @param {Object} data 字典数据
- * @returns list
- */
- export const dictToOptions = (data: any) => {
- return Object.keys(data).map((k) => {
- const kstr = typeof k === "number" ? k : k + "";
- return { value: kstr, label: data[k] };
- });
- };
- /**
- * 获取随机code,默认获取16位
- * @param {Number} len 推荐8的倍数
- *
- */
- export function randomCode(len = 16) {
- if (len <= 0) return;
- let steps = Math.ceil(len / 8);
- let stepNums = [];
- for (let i = 0; i < steps; i++) {
- let ranNum = Math.random().toString(32).slice(-8);
- stepNums.push(ranNum);
- }
- return stepNums.join("");
- }
- export function setValueFromObj(targetObj: any, fromObj: any) {
- fromObj = fromObj ? fromObj : {};
- let keys = Object.keys(targetObj);
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i];
- if (fromObj.hasOwnProperty(key)) {
- targetObj[key] = fromObj[key];
- }
- }
- return targetObj;
- }
|