文件下载
export class DownloadRobot {
stream;
constructor() {}
pick(stream) {
this.stream = stream;
return this;
}
put(name) {
var blob = new Blob([this.stream.data], {
type: this.stream.type,
});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = name || '';
link.click();
window.URL.revokeObjectURL(link.href);
}
downUrl(fileName, url) {
let a = document.createElement('a');
a.href = url;
a.download = fileName;
a.click();
a.remove();
}
fileRead(text) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => {
const { result } = reader;
resolve(JSON.parse(result));
};
reader.readAsText(text);
});
}
}
使用
const downloadRobot = new DownloadRobot()
downloadRobot.pick(res)
downloadRobot.put(fileList[0].name)
downloadRobot.downUrl(item.fileName, item.fileUrl)
获取URL参数
export function getQueryObject(url) {
url = url == null ? window.location.href : url
const search = url.substring(url.lastIndexOf('?') + 1)
const obj = {}
const reg = /([^?&=]+)=([^?&=]*)/g
search.replace(reg, (rs, $1, $2) => {
const name = decodeURIComponent($1)
let val = decodeURIComponent($2)
val = String(val)
obj[name] = val
return rs
})
return obj
}
获取字节长度
export function byteLength(str) {
let s = str.length
for (var i = str.length - 1; i >= 0; i--) {
const code = str.charCodeAt(i)
if (code > 0x7f && code <= 0x7ff) s++
else if (code > 0x7ff && code <= 0xffff) s += 2
if (code >= 0xdc00 && code <= 0xdfff) i--
}
return s
}
是不是数字字符串
export function isNumberStr(str) {
return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}
下划转驼峰
export function camelCase(str) {
return str.replace(/_[a-z]/g, (str1) => str1.substr(-1).toUpperCase())
}
首字母大小
export function titleCase(str) {
return str.replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
}
验证是否为blob格式
export async function blobValidate(data) {
try {
const text = await data.text();
JSON.parse(text);
return false;
} catch (error) {
return true;
}
}
构造树型结构数据
export function handleTree(data, id, parentId, children) {
let config = {
id: id || 'id',
parentId: parentId || 'parentId',
childrenList: children || 'children'
};
var childrenListMap = {};
var nodeIds = {};
var tree = [];
for (let d of data) {
let parentId = d[config.parentId];
if (childrenListMap[parentId] == null) {
childrenListMap[parentId] = [];
}
nodeIds[d[config.id]] = d;
childrenListMap[parentId].push(d);
}
for (let d of data) {
let parentId = d[config.parentId];
if (nodeIds[parentId] == null) {
tree.push(d);
}
}
for (let t of tree) {
adaptToChildrenList(t);
}
function adaptToChildrenList(o) {
if (childrenListMap[o[config.id]] !== null) {
o[config.childrenList] = childrenListMap[o[config.id]];
}
if (o[config.childrenList]) {
for (let c of o[config.childrenList]) {
adaptToChildrenList(c);
}
}
}
return tree;
}