utils.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import { YYYYMMDDHHmmss } from "@/constant/constants";
  2. import moment from "moment";
  3. import queryString from "query-string";
  4. import MD5 from "js-md5";
  5. export function dateFormatForAPI(date) {
  6. return moment(date).format(YYYYMMDDHHmmss);
  7. }
  8. export function formatEmptyToNull(obj) {
  9. Object.keys(obj).forEach((key) => {
  10. obj[key] = obj[key] === "" || obj[key] === undefined ? null : obj[key];
  11. });
  12. return obj;
  13. }
  14. // 错误上报:本地打印,百度统计,阿里云日志
  15. export function errorLog(message, { stack = "", code = "" }) {
  16. console.error({ message, stack, code });
  17. window._hmt.push([
  18. "_trackEvent",
  19. "message: " + message,
  20. stack && "stack: " + stack,
  21. code && "code: " + code,
  22. ]);
  23. }
  24. const CryptoJS = require("crypto-js");
  25. export function AESString(content) {
  26. const KEY = "1234567890123456";
  27. const IV = "1234567890123456";
  28. // console.log(content);
  29. var key = CryptoJS.enc.Utf8.parse(KEY);
  30. var iv = CryptoJS.enc.Utf8.parse(IV);
  31. var encrypted = CryptoJS.AES.encrypt(content, key, { iv: iv });
  32. return encrypted.toString();
  33. }
  34. export function encodePassword(content) {
  35. return window.btoa(content);
  36. }
  37. export function object2QueryString(obj) {
  38. return queryString.stringify(obj);
  39. }
  40. function toDataURL(url) {
  41. return fetch(url)
  42. .then((response) => {
  43. return response.blob();
  44. })
  45. .then((blob) => {
  46. return URL.createObjectURL(blob);
  47. });
  48. }
  49. // 下载文件
  50. export async function downloadFileURL(url, name) {
  51. const link = document.createElement("a");
  52. link.style.display = "none";
  53. const fileName = name || url.split("/").pop().split("?")[0];
  54. link.setAttribute("download", fileName);
  55. // txt 文件会直接在浏览器里面打开,这时候只能修改服务器设置,加上 Content-Disposition: attachment
  56. if ([".txt"].some((v) => fileName.endsWith(v))) {
  57. // const urlObj = new URL(url);
  58. // link.href = await toDataURL(url.replace(urlObj.origin));
  59. link.href = await toDataURL(url);
  60. } else {
  61. link.href = url;
  62. }
  63. document.body.appendChild(link);
  64. link.click();
  65. document.body.removeChild(link);
  66. }
  67. /**
  68. * 将目标对象中有的属性值与源对象中的属性值合并
  69. * @param {Object} target 目标对象
  70. * @param {Object} sources 源对象
  71. */
  72. export function objAssign(target, sources) {
  73. let targ = { ...target };
  74. for (let k in targ) {
  75. targ[k] = Object.prototype.hasOwnProperty.call(sources, k)
  76. ? sources[k]
  77. : targ[k];
  78. }
  79. return targ;
  80. }
  81. function parseDownloadFilename(dispositionInfo) {
  82. const strs = dispositionInfo.split(";");
  83. let filename = "";
  84. strs
  85. .map((item) => item.split("="))
  86. .find((item) => {
  87. if (item[0].indexOf("filename") !== -1) {
  88. filename = decodeURI(item[1]);
  89. }
  90. });
  91. return filename;
  92. }
  93. /**
  94. * 文件流下载
  95. * @param {Function} fetchFunc 下载程序,返回promise
  96. * @param {String} fileName 保存的文件名
  97. */
  98. export async function downloadBlob(fetchFunc, fileName) {
  99. const res = await fetchFunc().catch(() => {});
  100. if (!res) return;
  101. const filename =
  102. fileName || parseDownloadFilename(res.headers["content-disposition"]);
  103. const blobUrl = URL.createObjectURL(new Blob([res.data]));
  104. let a = document.createElement("a");
  105. a.download = filename;
  106. a.href = blobUrl;
  107. document.body.appendChild(a);
  108. a.click();
  109. a.parentNode.removeChild(a);
  110. return true;
  111. }
  112. export function objTypeOf(obj) {
  113. const toString = Object.prototype.toString;
  114. const map = {
  115. "[object Boolean]": "boolean",
  116. "[object Number]": "number",
  117. "[object String]": "string",
  118. "[object Function]": "function",
  119. "[object Array]": "array",
  120. "[object Date]": "date",
  121. "[object RegExp]": "regExp",
  122. "[object Undefined]": "undefined",
  123. "[object Null]": "null",
  124. "[object Object]": "object",
  125. };
  126. return map[toString.call(obj)];
  127. }
  128. export function formatDate(format = "YYYY/MM/DD HH:mm:ss", date = new Date()) {
  129. if (objTypeOf(date) !== "date") return;
  130. const options = {
  131. "Y+": date.getFullYear(),
  132. "M+": date.getMonth() + 1,
  133. "D+": date.getDate(),
  134. "H+": date.getHours(),
  135. "m+": date.getMinutes(),
  136. "s+": date.getSeconds(),
  137. };
  138. Object.entries(options).map(([key, val]) => {
  139. if (new RegExp("(" + key + ")").test(format)) {
  140. const zeros = key === "Y+" ? "0000" : "00";
  141. const value = (zeros + val).substr(("" + val).length);
  142. format = format.replace(RegExp.$1, value);
  143. }
  144. });
  145. return format;
  146. }
  147. /**
  148. * 获取时间长度文字
  149. * @param {Number} timeNumber 时间数值,单位:毫秒
  150. */
  151. export function timeNumberToText(timeNumber) {
  152. const DAY_TIME = 24 * 60 * 60 * 1000;
  153. const HOUR_TIME = 60 * 60 * 1000;
  154. const MINUTE_TIME = 60 * 1000;
  155. const SECOND_TIME = 1000;
  156. let [day, hour, minute, second] = [0, 0, 0, 0];
  157. let residueTime = timeNumber;
  158. if (residueTime >= DAY_TIME) {
  159. day = Math.floor(residueTime / DAY_TIME);
  160. residueTime -= day * DAY_TIME;
  161. day += "天";
  162. }
  163. if (residueTime >= HOUR_TIME) {
  164. hour = Math.floor(residueTime / HOUR_TIME);
  165. residueTime -= hour * HOUR_TIME;
  166. hour += "小时";
  167. }
  168. if (residueTime >= MINUTE_TIME) {
  169. minute = Math.floor(residueTime / MINUTE_TIME);
  170. residueTime -= minute * MINUTE_TIME;
  171. minute += "分钟";
  172. }
  173. if (residueTime >= SECOND_TIME) {
  174. second = Math.round(residueTime / SECOND_TIME);
  175. second += "秒";
  176. }
  177. return [day, hour, minute, second].filter((item) => !!item).join("");
  178. }
  179. export function deepCopy(obj) {
  180. return JSON.parse(JSON.stringify(obj));
  181. }
  182. /** @param blob {Blob} File is a type of Blob */
  183. export async function getMd5FromBlob(blob) {
  184. async function blobToArray(blob) {
  185. return new Promise((resolve) => {
  186. var reader = new FileReader();
  187. reader.addEventListener("loadend", function () {
  188. // reader.result contains the contents of blob as a typed array
  189. resolve(reader.result);
  190. });
  191. reader.readAsArrayBuffer(blob);
  192. });
  193. }
  194. const ab = await blobToArray(blob);
  195. return MD5(ab);
  196. }
  197. /**
  198. * 获取随机code,默认获取16位
  199. * @param {Number} len 推荐8的倍数
  200. *
  201. */
  202. export function randomCode(len = 16) {
  203. if (len <= 0) return;
  204. let steps = Math.ceil(len / 8);
  205. let stepNums = [];
  206. for (let i = 0; i < steps; i++) {
  207. let ranNum = Math.random().toString(32).slice(-8);
  208. stepNums.push(ranNum);
  209. }
  210. return stepNums.join("");
  211. }