beelink/src/utils/common.ts
2020-11-26 16:44:58 +08:00

116 lines
2.7 KiB
TypeScript

import { message } from 'ant-design-vue';
import { geti18n } from './i18n';
/**
* 图片转Base64
*/
function getBase64(file: File): Promise<string | ArrayBuffer | null> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
/**
* 预览图片
*/
export async function previewCover(file: any): Promise<string> {
if (!file.url && !file.preview) {
file.preview = await getBase64(file.originFileObj);
}
return file.url || file.preview || '';
}
/**
* 存储对应key
* @param key 键值
* @param value 内容 object自动序列化
*/
export function saveValue(key: string, value: any): boolean{
if(typeof value == 'object'){
value = JSON.stringify(value)
}
try {
localStorage.setItem(key, value);
return true;
} catch (error) {
return false;
}
}
/**
* 获取对应key
* @param key 键值
*/
export function getValue(key: string): any{
let value = localStorage.getItem(key);
if(value != null){
try {
value = JSON.parse(value);
} catch (error) {
return value;
}
}
return value;
}
/**
* 验证图片是否为对应类型
* @param name 图片名字
*/
export function provenimg(file: any): boolean | void{
const lan = geti18n()
const type = ['png', 'jpg'];
const ntypearr = file.name.split('.');
const ntype = ntypearr[ntypearr.length - 1];
console.log(ntype)
const size = 2 * 1024 * 1024;
if(file.size > size){
message.error(lan.$t('zuida') + "2MB")
return false;
}
let istype = false
for(const i in type){
if(type[i] == ntype){
istype = true
}
}
console.log(istype)
return istype;
}
/**
* 验证视频是否为对应类型
* @param name 图片名字
*/
export function provenvideo(file: any, isvideo?: boolean): boolean{
const lan = geti18n()
const type = ['flv', 'mp4', 'wmv', 'mov', 'avi'];
const ntypearr = file.name.split('.');
const ntype = ntypearr[ntypearr.length - 1];
if(isvideo){
const size = 500 * 1024 * 1024;
if(file.size > size){
message.error(lan.$t('zuida') + "500MB")
return false;
}
}else{
const size = 100 * 1024 * 1024;
if(file.size > size){
message.error(lan.$t('zuida') + "100MB")
return false;
}
}
for(const i in type){
if(type[i] == ntype){
return true;
}
}
message.error(lan.$t("leixingcuowu"))
return false;
}