1==================獲取uuid======================== export function createUuid() { const lut = [] for (let i = 0; i < 256; i++) { lut[i] = (i < 16 ? '0' : '') + i.toString(16) } const d0 = (Math.random() * 0xffffffff) | 0 const d1 = (Math.random() * 0xffffffff) | 0 const d2 = (Math.random() * 0xffffffff) | 0 const d3 = (Math.random() * 0xffffffff) | 0 return ( lut[d0 & 0xff] + lut[(d0 >> 8) & 0xff] + lut[(d0 >> 16) & 0xff] + lut[(d0 >> 24) & 0xff] + lut[d1 & 0xff] + lut[(d1 >> 8) & 0xff] + '-' + lut[((d1 >> 16) & 0x0f) | 0x40] + lut[(d1 >> 24) & 0xff] + lut[(d2 & 0x3f) | 0x80] + lut[(d2 >> 8) & 0xff] + '-' + lut[(d2 >> 16) & 0xff] + lut[(d2 >> 24) & 0xff] + lut[d3 & 0xff] + lut[(d3 >> 8) & 0xff] + lut[(d3 >> 16) & 0xff] + lut[(d3 >> 24) & 0xff] ) } ================自動話語 export function timeFix() { const time = new Date() const hour = time.getHours() return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好' } export function welcome() { const arr = ['休息一會兒吧', '准備吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了'] const index = Math.floor(Math.random() * arr.length) return arr[index] } /** * 觸發 window.resize */ export function triggerWindowResizeEvent() { const event = document.createEvent('HTMLEvents') event.initEvent('resize', true, true) event.eventType = 'message' window.dispatchEvent(event) } export function handleScrollHeader(callback) { let timer = 0 let beforeScrollTop = window.pageYOffset callback = callback || function() {} window.addEventListener( 'scroll', event => { clearTimeout(timer) timer = setTimeout(() => { let direction = 'up' const afterScrollTop = window.pageYOffset const delta = afterScrollTop - beforeScrollTop if (delta === 0) { return false } direction = delta > 0 ? 'down' : 'up' callback(direction) beforeScrollTop = afterScrollTop }, 50) }, false ) } /** * Remove loading animate * @param id parent element id or class * @param timeout */ export function removeLoadingAnimate(id = '', timeout = 1500) { if (id === '') { return } setTimeout(() => { document.body.removeChild(document.getElementById(id)) }, timeout) } export function millsToTime(mills) { if (!mills) { return '' } const s = mills / 1000 if (s < 60) { return s.toFixed(0) + ' 秒' } const m = s / 60 if (m < 60) { return m.toFixed(0) + ' 分鍾' } const h = m / 60 if (h < 24) { return h.toFixed(0) + ' 小時' } const d = h / 24 if (d < 30) { return d.toFixed(0) + ' 天' } const month = d / 30 if (month < 12) { return month.toFixed(0) + ' 個月' } const year = month / 12 return year.toFixed(0) + ' 年' } /* 生成UUID, 指定長度和基數 */ export function uuid(len, radix) { var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('') var uuid = [] radix = radix || chars.length if (len) { // Compact form for (let i = 0; i < len; i++) { uuid[i] = chars[0 | (Math.random() * radix)] } } else { // rfc4122, version 4 form var r // rfc4122 requires these characters uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-' uuid[14] = '4' // Fill in random data. At i==19 set the high bits of clock sequence as // per rfc4122, sec. 4.1.5 for (let i = 0; i < 64; i++) { if (!uuid[i]) { r = 0 | (Math.random() * 16) uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r] } } } return uuid.join('') } /** * 判斷對象是否為數組 * @param arr */ export function isArray(arr) { return arr && Object.prototype.toString.call(arr) === '[object Array]' } /** * 為當前url添加參數 * @param uri 當前uri * @param key 參數名 * @param value 參數值 */ export function updateQueryStringParameter(uri, key, value) { if (!value || !key) { return uri } var re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i') var separator = uri.indexOf('?') !== -1 ? '&' : '?' if (uri.match(re)) { return uri.replace(re, '$1' + key + '=' + value + '$2') } else { return uri + separator + key + '=' + value } } /** * 實時時間轉換指令,大於一個月則返回具體的年月日 * @param { string } timeStamp - 時間 格式:年-月-日 時:分:秒 或 時間戳 * @returns { string } */ export function getFormatTime(timeStamp) { var dateTime = new Date(timeStamp) var no1new = dateTime.valueOf() var year = dateTime.getFullYear() var month = dateTime.getMonth() + 1 var day = dateTime.getDate() var hour = dateTime.getHours() var minute = dateTime.getMinutes() var second = dateTime.getSeconds() var now = new Date() var nowNew = now.valueOf() var milliseconds = 0 var timeSpanStr milliseconds = nowNew - no1new if (milliseconds <= 1000 * 60 * 1) { timeSpanStr = '剛剛' } else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) { timeSpanStr = Math.round(milliseconds / (1000 * 60)) + '分鍾前' } else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) { timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小時前' } else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) { timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前' } else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year === now.getFullYear()) { // timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second timeSpanStr = year + '-' + month + '-' + day } else { // timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second timeSpanStr = year + '-' + month + '-' + day } return timeSpanStr } /** * 下載文件 */ export function resolveBlob(response) { const data = response.data if (!data) { return } const contentDisposition = response.headers['content-disposition'] const fileName = decodeURIComponent(contentDisposition.substring(contentDisposition.indexOf('=') + 1)) const url = window.URL.createObjectURL(new Blob([data])) const a = document.createElement('a') a.style.display = 'none' a.href = url a.setAttribute('download', fileName) document.body.appendChild(a) // 點擊下載 a.click() // 下載完成移除元素 document.body.removeChild(a) // 釋放掉blob對象 window.URL.revokeObjectURL(url) } /** * 字節B轉化成KB,MB,GB */ export function formatByte(limit) { limit = parseInt(limit) let size = '' if (limit < 1024) { // 小於1KB, 則轉化成B size = limit.toFixed(2) + 'B' } else if (limit < 1024 * 1024) { // 小於1MB, 則轉化成KB size = (limit / 1024).toFixed(2) + 'KB' } else if (limit < 1024 * 1024 * 1024) { // 小於1GB, 則轉化成MB size = (limit / (1024 * 1024)).toFixed(2) + 'MB' } else { // 其他轉化成GB size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB' } const sizeStr = size + '' // 轉成字符串 const index = sizeStr.indexOf('.') // 獲取小數點處的索引 const dou = sizeStr.substr(index + 1, 2) // 獲取小數點后兩位的值 if (dou === '00') { return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2) } return size } /** * 設置sessionStorage屬性 * @param key 鍵名 * @param value 值 */ export function setSessionStorage(key, value) { if (!key) { console.log(new Error('存儲sessionStorage的Key必須為非假值')) return } sessionStorage.setItem(key, JSON.stringify(value)) } /** * 獲取sessionStorage屬性 * @param key 鍵名 * @param isJson 是否返回json格式 */ export function getSessionStorage(key, isJson = false) { if (!key) { console.log(new Error('存儲sessionStorage的Key必須為非假值')) return } const jsonStr = sessionStorage.getItem(key) return isJson ? jsonStr : JSON.parse(jsonStr) }
==================================文件下載上傳====================================
import { pureAxios, axios } from '@/utils/request' import { resolveBlob, createUuid, formatByte } from '@/utils/util' import { notification, Modal } from 'ant-design-vue' const { confirm } = Modal const api = { tSysFile: '/pts/sys/TSysFile' } const mimeMap = { xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', zip: 'application/zip', xml: 'application/xml', doc: 'application/msword' } export function downloadTSysFile(parameter) { const key = createUuid() pureAxios({ url: api.tSysFile + '/download', method: 'post', params: parameter, responseType: 'blob', onDownloadProgress(progress) { var total = progress.srcElement.getResponseHeader('content-length') const allProgress = Math.round(progress.loaded / total * 100) const loadedSize = formatByte(progress.loaded) const totalSize = formatByte(total) notification.open({ key, message: '下載進度:' + loadedSize + ' / ' + totalSize, duration: null, description: h => { return h( 'a-progress', { props: { percent: allProgress, size: 'small', status: 'active' }, on: { click: () => this.$notification.close(key) } }, '' ) }, onClose: () => { confirm({ title: '確定取消下載?', onOk() { progress.srcElement.abort() notification.close(key) }, onCancel() { } }) }, icon: h => { return h( 'a-icon', { props: { type: 'cloud-download' } }, '' ) } }) } }) .then(response => { resolveBlob(response) notification.close(key) }) .catch(error => { console.log(error) }) } export function getTSysFile(parameter) { pureAxios({ url: api.tSysFile + '/download', method: 'post', params: parameter, responseType: 'blob' }) } export function getBackupInfo(parameter, back) { pureAxios({ url: '/backup/download', method: 'post', params: parameter, responseType: 'blob' }).then(res => { resolveBlob(res, mimeMap.zip) if (back) { back() } }) }