日常工具方法集

一、本地存储之localStorage和sessionStorage


// Storage方法集
export const storage = {
	/**
	 * 存储Storage
	 * @param {string} key 要存储的key
	 * @param {any} value 要存储的值
	 * @param {boolean} isLocal 是否为localStorage,默认值:true
	 * @returns
	 */
	set(key: string, value: any, isLocal = true) {
		if (!key || typeof key !== 'string') {
			console.log('参数错误:缺少必要参数key或key数据类型不为string');
			return;
		}

		if (typeof value !== 'string') {
			try {
				value = JSON.stringify(value);
			} catch (error) {
				console.log('JSON.stringify Error:', error);
			}
		}

		const storage = isLocal ? localStorage : sessionStorage;
		storage.setItem(key, value);
	},
	/**
	 * 获取Storage
	 * @param {string} key 要获取的key
	 * @param {any} defaultVal 获取的key值为空时的默认值
	 * @param {boolean} isLocal 是否为localStorage,默认值:true
	 * @returns
	 */
	get(key: string, defaultVal?: any, isLocal = true) {
		if (!key || typeof key !== 'string') {
			console.log('参数错误:缺少必要参数key或key数据类型不为string');
			return;
		}

		const storage = isLocal ? localStorage : sessionStorage;
		const value = storage.getItem(key);

		if (!value) {
			return defaultVal;
		}

		try {
			return JSON.parse(value);
		} catch (error) {
			return value;
		}
	},
	/**
	 * 移除Storage
	 * @param {string|string[]} key 要删除的key或key数组
	 * @param {boolean} isLocal 是否为localStorage,默认值:true
	 * @returns
	 */
	remove(key: string | string[], isLocal = true) {
		if (!key) {
			console.log('参数错误:缺少必要参数key');
			return;
		}

		const storage = isLocal ? localStorage : sessionStorage;
		if (Array.isArray(key)) {
			key.forEach((item) => {
				storage.removeItem(item);
			});
			return;
		}
		storage.removeItem(key);
	},
	/**
	 * 清空Storage
	 * @param {boolean} isLocal 是否为localStorage,默认值:true
	 * @returns
	 */
	clear(isLocal = true) {
		const storage = isLocal ? localStorage : sessionStorage;
		storage.clear();
	},
};

二、解析地址栏参数

支持手动传参要解析的串和默认获取地址栏携带参数地址串

// 解析地址栏参数
export function getUrlParams(urlSearch?: string) {
  let searchStr;
  if (typeof urlSearch === "undefined") {
    searchStr = window.location.href.split("?")[1] || ""; // 获取url中"?"符后的字符串
  } else {
    const urlSearchArr = urlSearch.split("?");
    searchStr = urlSearchArr[1] || urlSearchArr[0] || "";
  }

  const paramsObj: any = {};
  const searchArr = searchStr.split("&");
  searchArr.forEach((item) => {
    if (!item || !item.includes("=")) return;

    const keyVal = item.split("=");
    const key = keyVal[0];
    // 没有key 跳过
    if (!key) return;

    const value = keyVal[1];
    paramsObj[key] = decodeURIComponent(value);
  });
  return paramsObj;
}

三、base64、blob、file之间的部分转换

// base64转blob
export function dataURItoBlob(base64Data: string, type: string = "video/mp4"): Blob {
  const strArr = base64Data.split(",");
  const prefixStr = strArr[0];
  let byteString = "";
  let mimeString = type;
  if (prefixStr.indexOf("base64") >= 0) {
    byteString = strArr[1] || "";
    const prefixStrArr = prefixStr.split(":");
    const mimeStringWithSemicolon = prefixStrArr[1] || "";
    mimeString = mimeStringWithSemicolon.split(";")[0];
  } else {
    byteString = decodeURIComponent(base64Data);
  }

  try {
    byteString = atob(byteString);
  } catch (error) {
    console.log("atob error:", (error as Error).message);
  }

  var ia = new Uint8Array(byteString.length);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  const blob: any = new Blob([ia], { type: mimeString });
  blob.lastModifiedDate = new Date();
  blob.name = "blob";
  return blob;
}

// blob转file
export function blobToFile(blobData: Blob, type = "video/mp4", fileName?: string): File {
  const date = new Date();
  const localDate = date.toISOString().split("T")[0];
  let timeDate = date.toTimeString().split(" ")[0];
  timeDate = timeDate.replace(/:/g, ".");
  const fileType = type.split("/")[1] || "";
  const _fileName = fileName || `${localDate}T${timeDate}.${fileType}`;
  const file = new File([blobData], _fileName, { type });
  return file;
}

// base64转file
export function base64ToFile(base64Url: string, type = "video/mp4", fileName?: string): File {
  const blob = dataURItoBlob(base64Url, type);
  const file = blobToFile(blob, type, fileName);
  return file;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值