文件下载
日期格式化
获取上一周的星期一
根据日期返回当前日期所在的星期一和星期天
获取当前日期的未来几天
获取当前日期的未来几个小时并格式化
获取当前日期的过去几个小时并格式化
时间戳转 “yy-mm-dd”
时间戳转 “yy-mm-dd hh:mm:ss”
判断是否为IE
import moment from "moment";
import { httpServer } from '@/api/config/axios'
import {saveAs} from 'file-saver'
/**
*通用下载方法
*downloadFile('请求方法(get/post)','请求地址url','入参',''文件名)
*调用案例:
*this.$util.downloadFile("post", "api/resources/resexport", {}, `a.xlsx`);
*/
function downloadFile(methods,url, data, filename) {
// downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
return httpServer[methods](url, data? data: '', {
responseType: 'blob'
}).then(async (res) => {
const isBlob = await blobValidate(res);
if (isBlob) {
const blob = new Blob([res])
saveAs(blob, filename)
} else {
const resText = await res.text();
const rspObj = JSON.parse(resText);
const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
Message.error(errMsg);
}
// downloadLoadingInstance.close();
}).catch((r) => {
console.error(r)
Message.error('下载文件出现错误,请联系管理员!')
downloadLoadingInstance.close();
})
}
// 验证是否为blob格式
export async function blobValidate(data) {
try {
const text = await data.text();
JSON.parse(text);
return false;
} catch (error) {
return true;
}
}
/* 时间格式化
formatDate (date, "yyyy-MM-dd")
*/
function formatDate (date, fmt) {
if(date==""||date==null){
return "";
}
let o = {
'M+': date.getMonth() + 1, // 月份
'd+': date.getDate(), // 日
'h+': date.getHours(), // 小时
'm+': date.getMinutes(), // 分
's+': date.getSeconds(), // 秒
'S': date.getMilliseconds() // 毫秒
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (var k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
}
}
return fmt
}
/**
* 获取上一周的星期一
* @param {Objec} day
* @returns
*/
function getLastWeek() {
let startDate = moment()
.week(moment().week() - 1)
.startOf("week")
.valueOf();
return moment(startDate).format("YYYY-MM-DD");
}
/**
* 根据日期返回当前日期所在的星期一和星期天
* @param {Objec} day
* @returns
*/
function getDayWeek(val) {
var t_day = val ? new Date(val) : new Date();
var tday_week = t_day.getDay();
let spendDay = 1;
if (tday_week != 0) {
spendDay = 7 - tday_week;
}
let startTimeStr = this.timeChangstr(t_day.valueOf() - (6 - spendDay) * 86400000);
let endTimeStr = this.timeChangstr(t_day.valueOf() + spendDay * 86400000);
return { startTimeStr, endTimeStr };
}
/**
* 获取当前日期的未来几天
* @param {Object} str
*/
function getNextDay(val,count) {
var today = val ? new Date(val) : new Date();
var tarTodayMin = today.getTime() + 1000 * 60 * 60 * 24 * count;
today.setTime(tarTodayMin);
var tY = today.getFullYear();
var tM = handleDay(today.getMonth() + 1);
var tD = handleDay(today.getDate());
return tY + "-" + tM + "-" + tD;
}
function handleDay(day) {
var d = day;
if (day.toString().length == 1) {
d = "0" + day;
}
return d;
}
/**
* 获取当前日期的未来几个小时并格式化
* @param {Object} str
*/
function getNextHour(val,count) {
var today = val ? new Date(val) : new Date();
var tarTodayMin = today.getTime() + 1000 * 60 * 60 * count;
today.setTime(tarTodayMin);
return this.formatDate(today,"yyyy-MM-dd hh");
}
/**
* 获取当前日期的过去几个小时并格式化
* @param {Object} str
*/
function getBeforeHour(val,count) {
var today = val ? new Date(val) : new Date();
var tarTodayMin = today.getTime() - 1000 * 60 * 60 * count;
today.setTime(tarTodayMin);
return this.formatDate(today,"yyyy-MM-dd hh");
}
/**
* 时间戳转 "yy-mm-dd"
* @param {Object} str
*/
function timeChangstr(time) {
// 时间戳为10位需*1000,时间戳为13位的话不需乘1000
if (time == null) {
return "-";
}
var date = new Date(time);
var Y = date.getFullYear() + "-";
var M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
return Y + M + D;
}
/**
* 时间戳转 "yy-mm-dd hh:mm:ss"
* @param {Object} str
*/
function timeChangstrMinute(time) {
if (time == null) {
return "-";
}
var date = new Date(time);
var Y = date.getFullYear() + "-";
var M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
var h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
var m = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
var s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
return Y + M + D + h + m + s;
}
/**
* 判断是否为IE
* @param {Object} str
*/
function getIsIE() {
if (!!window.ActiveXObject || "ActiveXObject" in window) return true;
else return false;
}
/**
* 防止传参脚本攻击
* @param {Object} str
*/
function preHTML(str) {
return str.toString().replace(/[<>"&]/g, function(val, index, allText) {
switch (val) {
case "<":
return "<";
case ">":
return ">";
/* eslint-disable */
case '"':
/* eslint-enable */
return """;
case "&":
return "&";
}
});
}
/**
* option 转换 string 传给后台
* @param {Object} str
*/
function optionToString(array, type) {
// option 转换 string 传给后台
var string = "";
if (array.length !== 0) {
string = array.join(",");
}
return string;
}
/**
* blob
* @param {Object} str
*/
function fileToSave(bdata, filename) {
var objectUrl = URL.createObjectURL(bdata);
var link = document.createElement("a");
link.style.display = "none";
link.href = objectUrl;
link.setAttribute("download", filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
/**
* 字节转换B Kb mb GB
* @param {Object} str
*/
function kbChange(limit) {
var size = "";
if (limit < 0.1 * 1024) {
size = limit.toFixed(2) + "B";
} else if (limit < 0.1 * 1024 * 1024) {
size = (limit / 1024).toFixed(2) + "KB";
} else if (limit < 0.1 * 1024 * 1024 * 1024) {
size = (limit / (1024 * 1024)).toFixed(2) + "MB";
} else {
size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
}
}
export default {
preHTML,
timeChangstr,
getIsIE,
optionToString,
getNewDay,
fileToSave,
kbChange,
getLastWeek,
timeChangstrMinute,
getDayWeek,
formatDate,
downloadFile,
getNextDay,
getNextHour,
getBeforeHour
};
封装get请求
封装post请求
请求拦截器
响应拦截器
import axios from "axios";
import baseurl from "./baseUrl";
import { Notice } from 'view-design';
import store from "../../store";
const httpServer = {};
const service = axios.create({
baseURL: baseurl.baseURL,
withCredentials: true, // 请求头cokkie
headers: {
"Content-Type": "application/json;charset=UTF-8"
},
maxContentLength: -1,
validateStatus(status) {
switch (status) {
case 400:
Notice.warning({
title: "警告",
desc: "请求出错"
});
break;
case 401:
Notice.warning({
title: "警告",
desc: "授权失败,请重新登录"
});
setTimeout(() => {
window.location.reload();
}, 1000);
break;
case 403:
Notice.error({
title: "警告",
desc: "请登录之后再进行访问,稍后跳回登录页面"
});
store.dispatch("loginOut");
// 跳转首页
break;
case 404:
Notice.warning({
title: "警告",
desc: "请求错误,未找到该接口资源"
});
break;
case 500:
Notice.warning({
title: "警告",
desc: "服务端错误"
});
break;
}
return status >= 200 && status < 300;
}
});
/*
* 请求拦截器
*/
service.interceptors.request.use(
config => {
// 添加token验证
// if(process.env.VUE_APP_IS_OPEN_CAS || window.GlobalConfig.TOB_IS_OPEN_CAS) {
if(window.GlobalConfig.TOB_IS_OPEN_CAS) {
const CASTGC = store.getters.cookieCas ? store.getters.cookieCas : '';
if(CASTGC === '') {
CASTGC = '123'
}
CASTGC && (config.headers.CASTGC = CASTGC);
}
return config;
},
error => {
return Promise.reject(error);
}
);
/*
* 响应拦截器
*/
service.interceptors.response.use(
response => {
let cas_code = response.data.code;
switch (cas_code) {
case 302:
Notice.error({
title: "警告",
desc: "请登录之后再进行访问,稍后跳回登录页面"
});
store.dispatch("loginOut");
break;
default:
return response;
}
},
error => {
// 服务器没返回结果
if (!window.navigator.onLine) {
// 断网跳转
Notice.warning({
title: "警告",
desc: "网络失去连接,请检查网络连接"
});
return;
}
return Promise.reject(error);
}
);
/**
* 封装 post get 方法
* 如果需要使用别的方法直接用service
*/
httpServer.get = (url, options) => {
return new Promise((resolve, reject) => {
service
.get(url, options)
.then(response => {
if (options !== undefined) {
resolve(response);
} else {
let data = response.data;
if (data.code === 0 || data.code === 1000) {
resolve(data.data);
} else {
Notice.error({
title: "警告",
desc: data.msg ? data.msg : '请求有误'
});
reject(data.msg);
}
}
})
.catch(e => {
Notice.error({
title: "警告",
desc: '请求有误'
});
reject(e);
});
});
};
httpServer.post = (url, data, options) => {
return new Promise((resolve, reject) => {
service
.post(url, data, options)
.then(response => {
let data = response.data;
if (options === undefined) {
if (data.code === 0 || data.code === 1000) {
resolve(data.data);
} else {
Notice.error({
title: "警告",
desc: '请求有误'
});
reject(data.msg);
}
} else {
resolve(data);
}
})
.catch(e => {
Notice.error({
title: "警告",
desc: '请求有误'
});
reject(e);
});
});
};
httpServer.request = (options) => {
return new Promise((resolve, reject) => {
service(options)
.then(response => {
const data = response.data;
if (options.responseType !== "blob") {
if (data.code === 200) {
resolve(data);
} else {
Notice.error({
title: "警告",
desc: data.msg ? data.msg : '请求有误'
});
reject(data.msg ? data.msg : data.message);
}
} else {
resolve(data);
}
})
.catch(e => {
console.log(e, "错误");
reject(e);
});
});
}
export { service, httpServer };