utils.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { YYYYMMDDHHmmss } from "@/constant/constants";
  2. import moment from "moment";
  3. import queryString from "query-string";
  4. export function dateFormatForAPI(date) {
  5. return moment(date).format(YYYYMMDDHHmmss);
  6. }
  7. export function formatEmptyToNull(obj) {
  8. Object.keys(obj).forEach((key) => {
  9. obj[key] = obj[key] === "" || obj[key] === undefined ? null : obj[key];
  10. });
  11. return obj;
  12. }
  13. // 错误上报:本地打印,百度统计,阿里云日志
  14. export function errorLog(message, { stack = "", code = "" }) {
  15. console.error({ message, stack, code });
  16. window._hmt.push([
  17. "_trackEvent",
  18. "message: " + message,
  19. stack && "stack: " + stack,
  20. code && "code: " + code,
  21. ]);
  22. }
  23. const CryptoJS = require("crypto-js");
  24. export function AESString(content) {
  25. const KEY = "1234567890123456";
  26. const IV = "1234567890123456";
  27. // console.log(content);
  28. var key = CryptoJS.enc.Utf8.parse(KEY);
  29. var iv = CryptoJS.enc.Utf8.parse(IV);
  30. var encrypted = CryptoJS.AES.encrypt(content, key, { iv: iv });
  31. return encrypted.toString();
  32. }
  33. export function object2QueryString(obj) {
  34. return queryString.stringify(obj);
  35. }
  36. function toDataURL(url) {
  37. return fetch(url)
  38. .then((response) => {
  39. return response.blob();
  40. })
  41. .then((blob) => {
  42. return URL.createObjectURL(blob);
  43. });
  44. }
  45. // 下载文件
  46. export async function downloadFileURL(url, name) {
  47. const link = document.createElement("a");
  48. link.style.display = "none";
  49. const fileName = name || url.split("/").pop();
  50. link.setAttribute("download", fileName);
  51. // txt 文件会直接在浏览器里面打开,这时候只能修改服务器设置,加上 Content-Disposition: attachment
  52. if ([".txt"].some((v) => fileName.endsWith(v))) {
  53. // const urlObj = new URL(url);
  54. // link.href = await toDataURL(url.replace(urlObj.origin));
  55. link.href = await toDataURL(url);
  56. } else {
  57. link.href = url;
  58. }
  59. document.body.appendChild(link);
  60. link.click();
  61. document.body.removeChild(link);
  62. }