tool.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. const storagePrefix = "cet_";
  2. /**
  3. * LocalStorage
  4. */
  5. export const local = {
  6. set(table: string, settings: any) {
  7. const _set = JSON.stringify(settings);
  8. return localStorage.setItem(storagePrefix + table, _set);
  9. },
  10. get(table: string) {
  11. let data: any = localStorage.getItem(storagePrefix + table);
  12. try {
  13. data = JSON.parse(data);
  14. } catch (err) {
  15. return null;
  16. }
  17. return data;
  18. },
  19. remove(table: string) {
  20. return localStorage.removeItem(storagePrefix + table);
  21. },
  22. clear() {
  23. return localStorage.clear();
  24. },
  25. };
  26. /**
  27. * SessionStorage
  28. */
  29. export const session = {
  30. set(table: string, settings: any) {
  31. const _set = JSON.stringify(settings);
  32. return sessionStorage.setItem(storagePrefix + table, _set);
  33. },
  34. get(table: string) {
  35. let data: any = sessionStorage.getItem(storagePrefix + table);
  36. try {
  37. data = JSON.parse(data);
  38. } catch (err) {
  39. return null;
  40. }
  41. return data;
  42. },
  43. remove(table: string) {
  44. return sessionStorage.removeItem(storagePrefix + table);
  45. },
  46. clear() {
  47. return sessionStorage.clear();
  48. },
  49. };
  50. export const clearStorage = () => {
  51. localStorage.clear();
  52. sessionStorage.clear();
  53. };
  54. export const generateId = function () {
  55. return Math.floor(
  56. Math.random() * 100000 + Math.random() * 20000 + Math.random() * 5000
  57. );
  58. };
  59. /* 日期格式化 */
  60. export const dateFormat = (
  61. date: any,
  62. fmt = "yyyy/MM/dd HH:mm:ss",
  63. isDefault = "-"
  64. ) => {
  65. if (!date) {
  66. return "-";
  67. }
  68. if (date.toString().length === 10) {
  69. date *= 1000;
  70. }
  71. date = new Date(date);
  72. if (date.valueOf() < 1) {
  73. return isDefault;
  74. }
  75. const o: any = {
  76. "M+": date.getMonth() + 1, // 月份
  77. "d+": date.getDate(), // 日
  78. "H+": date.getHours(), // 小时
  79. "m+": date.getMinutes(), // 分
  80. "s+": date.getSeconds(), // 秒
  81. "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
  82. S: date.getMilliseconds(), // 毫秒
  83. };
  84. if (/(y+)/.test(fmt)) {
  85. fmt = fmt.replace(
  86. RegExp.$1,
  87. `${date.getFullYear()}`.substr(4 - RegExp.$1.length)
  88. );
  89. }
  90. for (const k in o) {
  91. if (new RegExp(`(${k})`).test(fmt)) {
  92. fmt = fmt.replace(
  93. RegExp.$1,
  94. RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length)
  95. );
  96. }
  97. }
  98. return fmt;
  99. };
  100. export const extractFileName = (str: string) => {
  101. if (/filename=([^;\s]*)/gi.test(str)) {
  102. return decodeURIComponent(RegExp.$1);
  103. }
  104. return "下载文件";
  105. };
  106. export const download = (res: any, downName = "") => {
  107. const aLink = document.createElement("a");
  108. let fileName = downName;
  109. let blob = res; // 第三方请求返回blob对象
  110. // 通过后端接口返回
  111. if (res.headers && res.data) {
  112. blob = new Blob([res.data], {
  113. type: res.headers["content-type"].replace(";charset=utf8", ""),
  114. });
  115. if (!downName) {
  116. fileName = extractFileName(res.headers?.["content-disposition"]);
  117. }
  118. }
  119. aLink.href = URL.createObjectURL(blob);
  120. // 设置下载文件名称
  121. aLink.setAttribute("download", fileName);
  122. document.body.appendChild(aLink);
  123. aLink.click();
  124. document.body.removeChild(aLink);
  125. URL.revokeObjectURL(aLink.href);
  126. };
  127. /**
  128. * 下载url
  129. * @param {String} url 文件下载地址
  130. * @param {String}} filename 文件名
  131. */
  132. export function downloadByUrl(url: string, filename: string) {
  133. const tempLink = document.createElement("a");
  134. tempLink.style.display = "none";
  135. tempLink.href = url;
  136. const fileName =
  137. filename || url.split("/").pop()?.split("?")[0] || "未命名文件";
  138. tempLink.setAttribute("download", fileName);
  139. if (tempLink.download === "undefined") {
  140. tempLink.setAttribute("target", "_blank");
  141. }
  142. document.body.appendChild(tempLink);
  143. tempLink.click();
  144. document.body.removeChild(tempLink);
  145. window.URL.revokeObjectURL(url);
  146. }
  147. export function urlToBlob(url: string, cb: Function) {
  148. const xhr = new XMLHttpRequest();
  149. xhr.open("GET", url, true);
  150. xhr.responseType = "blob";
  151. xhr.onload = function () {
  152. if (xhr.status == 200) {
  153. cb(URL.createObjectURL(xhr.response));
  154. }
  155. };
  156. xhr.send();
  157. }
  158. export function saveAs(blob: Blob, filename: string) {
  159. if ((window as any).navigator.msSaveOrOpenBlob) {
  160. (navigator as any).msSaveBlob(blob, filename);
  161. } else {
  162. var link: any = document.createElement("a");
  163. var body = document.querySelector("body") as HTMLBodyElement;
  164. link.href = blob;
  165. link.download = filename;
  166. link.style.display = "none";
  167. body.appendChild(link);
  168. link.click();
  169. body.removeChild(link);
  170. window.URL.revokeObjectURL(link.href);
  171. }
  172. }
  173. export function downloadByCrossUrl(url: string, filename: string) {
  174. urlToBlob(url, (blob: Blob) => {
  175. saveAs(blob, filename);
  176. });
  177. }
  178. export const getRequestParams = (url: string) => {
  179. const theRequest: any = new Object();
  180. if (url.indexOf("?") != -1) {
  181. const params = url.split("?")[1].split("&");
  182. for (let i = 0; i < params.length; i++) {
  183. const param = params[i].split("=");
  184. theRequest[param[0]] = decodeURIComponent(param[1]);
  185. }
  186. }
  187. return theRequest;
  188. };
  189. /**
  190. * 字典数据转成option list
  191. * @param {Object} data 字典数据
  192. * @returns list
  193. */
  194. export const dictToOptions = (data: any) => {
  195. return Object.keys(data).map((k) => {
  196. const kstr = typeof k === "number" ? k : k + "";
  197. return { value: kstr, label: data[k] };
  198. });
  199. };
  200. /**
  201. * 获取随机code,默认获取16位
  202. * @param {Number} len 推荐8的倍数
  203. *
  204. */
  205. export function randomCode(len = 16) {
  206. if (len <= 0) return;
  207. let steps = Math.ceil(len / 8);
  208. let stepNums = [];
  209. for (let i = 0; i < steps; i++) {
  210. let ranNum = Math.random().toString(32).slice(-8);
  211. stepNums.push(ranNum);
  212. }
  213. return stepNums.join("");
  214. }
  215. export function setValueFromObj(targetObj: any, fromObj: any) {
  216. fromObj = fromObj ? fromObj : {};
  217. let keys = Object.keys(targetObj);
  218. for (let i = 0; i < keys.length; i++) {
  219. const key = keys[i];
  220. if (fromObj.hasOwnProperty(key)) {
  221. targetObj[key] = fromObj[key];
  222. }
  223. }
  224. return targetObj;
  225. }