123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256 |
- import { YYYYMMDDHHmmss } from "@/constant/constants";
- import moment from "moment";
- import queryString from "query-string";
- import MD5 from "js-md5";
- export function dateFormatForAPI(date) {
- return moment(date).format(YYYYMMDDHHmmss);
- }
- export function timeFormatForAPI(date) {
- return moment(date).format("HH:mm:ss");
- }
- export function formatEmptyToNull(obj) {
- Object.keys(obj).forEach((key) => {
- obj[key] = obj[key] === "" || obj[key] === undefined ? null : obj[key];
- });
- return obj;
- }
- // 错误上报:本地打印,百度统计,阿里云日志
- export function errorLog(message, { stack = "", code = "" }) {
- console.error({ message, stack, code });
- window._hmt.push([
- "_trackEvent",
- "message: " + message,
- stack && "stack: " + stack,
- code && "code: " + code,
- ]);
- }
- const CryptoJS = require("crypto-js");
- export function AESString(content) {
- const KEY = "1234567890123456";
- const IV = "1234567890123456";
- // console.log(content);
- var key = CryptoJS.enc.Utf8.parse(KEY);
- var iv = CryptoJS.enc.Utf8.parse(IV);
- var encrypted = CryptoJS.AES.encrypt(content, key, { iv: iv });
- return encrypted.toString();
- }
- export function encodePassword(content) {
- return window.btoa(content);
- }
- export function object2QueryString(obj) {
- return queryString.stringify(obj);
- }
- function toDataURL(url) {
- return fetch(url)
- .then((response) => {
- return response.blob();
- })
- .then((blob) => {
- return URL.createObjectURL(blob);
- });
- }
- // 下载文件
- export async function downloadFileURL(url, name) {
- const link = document.createElement("a");
- link.style.display = "none";
- const fileName = name || url.split("/").pop().split("?")[0];
- link.setAttribute("download", fileName);
- // txt 文件会直接在浏览器里面打开,这时候只能修改服务器设置,加上 Content-Disposition: attachment
- if ([".txt"].some((v) => fileName.endsWith(v))) {
- // const urlObj = new URL(url);
- // link.href = await toDataURL(url.replace(urlObj.origin));
- link.href = await toDataURL(url);
- } else {
- link.href = url;
- }
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- }
- /**
- * 将目标对象中有的属性值与源对象中的属性值合并
- * @param {Object} target 目标对象
- * @param {Object} sources 源对象
- */
- export function objAssign(target, sources) {
- let targ = { ...target };
- for (let k in targ) {
- targ[k] = Object.prototype.hasOwnProperty.call(sources, k)
- ? sources[k]
- : targ[k];
- }
- return targ;
- }
- function parseDownloadFilename(dispositionInfo) {
- const strs = dispositionInfo.split(";");
- let filename = "";
- strs
- .map((item) => item.split("="))
- .find((item) => {
- if (item[0].indexOf("filename") !== -1) {
- filename = decodeURI(item[1]);
- }
- });
- return filename;
- }
- /**
- * 文件流下载
- * @param {Function} fetchFunc 下载程序,返回promise
- * @param {String} fileName 保存的文件名
- */
- export async function downloadBlob(fetchFunc, fileName) {
- const res = await fetchFunc().catch(() => {});
- if (!res) return;
- const filename =
- fileName || parseDownloadFilename(res.headers["content-disposition"]);
- const blobUrl = URL.createObjectURL(new Blob([res.data]));
- let a = document.createElement("a");
- a.download = filename;
- a.href = blobUrl;
- document.body.appendChild(a);
- a.click();
- a.parentNode.removeChild(a);
- return true;
- }
- export function objTypeOf(obj) {
- const toString = Object.prototype.toString;
- const map = {
- "[object Boolean]": "boolean",
- "[object Number]": "number",
- "[object String]": "string",
- "[object Function]": "function",
- "[object Array]": "array",
- "[object Date]": "date",
- "[object RegExp]": "regExp",
- "[object Undefined]": "undefined",
- "[object Null]": "null",
- "[object Object]": "object",
- };
- return map[toString.call(obj)];
- }
- export function formatDate(format = "YYYY/MM/DD HH:mm:ss", date = new Date()) {
- if (objTypeOf(date) !== "date") return;
- const options = {
- "Y+": date.getFullYear(),
- "M+": date.getMonth() + 1,
- "D+": date.getDate(),
- "H+": date.getHours(),
- "m+": date.getMinutes(),
- "s+": date.getSeconds(),
- };
- Object.entries(options).map(([key, val]) => {
- if (new RegExp("(" + key + ")").test(format)) {
- const zeros = key === "Y+" ? "0000" : "00";
- const value = (zeros + val).substr(("" + val).length);
- format = format.replace(RegExp.$1, value);
- }
- });
- return format;
- }
- /**
- * 获取时间长度文字
- * @param {Number} timeNumber 时间数值,单位:毫秒
- */
- export function timeNumberToText(timeNumber) {
- const DAY_TIME = 24 * 60 * 60 * 1000;
- const HOUR_TIME = 60 * 60 * 1000;
- const MINUTE_TIME = 60 * 1000;
- const SECOND_TIME = 1000;
- let [day, hour, minute, second] = [0, 0, 0, 0];
- let residueTime = timeNumber;
- if (residueTime >= DAY_TIME) {
- day = Math.floor(residueTime / DAY_TIME);
- residueTime -= day * DAY_TIME;
- day += "天";
- }
- if (residueTime >= HOUR_TIME) {
- hour = Math.floor(residueTime / HOUR_TIME);
- residueTime -= hour * HOUR_TIME;
- hour += "小时";
- }
- if (residueTime >= MINUTE_TIME) {
- minute = Math.floor(residueTime / MINUTE_TIME);
- residueTime -= minute * MINUTE_TIME;
- minute += "分钟";
- }
- if (residueTime >= SECOND_TIME) {
- second = Math.round(residueTime / SECOND_TIME);
- second += "秒";
- }
- return [day, hour, minute, second].filter((item) => !!item).join("");
- }
- export function deepCopy(obj) {
- return JSON.parse(JSON.stringify(obj));
- }
- /** @param blob {Blob} File is a type of Blob */
- export async function getMd5FromBlob(blob) {
- async function blobToArray(blob) {
- return new Promise((resolve) => {
- var reader = new FileReader();
- reader.addEventListener("loadend", function () {
- // reader.result contains the contents of blob as a typed array
- resolve(reader.result);
- });
- reader.readAsArrayBuffer(blob);
- });
- }
- const ab = await blobToArray(blob);
- return MD5(ab);
- }
- /**
- * 获取随机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 snakeToHump(content) {
- let cont = content.toLowerCase().split("_");
- return cont.map((item) => item[0].toUpperCase() + item.substr(1)).join("");
- }
- /**
- * 计算总数
- * @param {Array} dataList 需要统计的数组
- */
- export function calcSum(dataList) {
- if (!dataList.length) return 0;
- return dataList.reduce(function (total, item) {
- return total + item;
- }, 0);
- }
|