WeKnora/frontend/src/utils/index.ts

67 lines
2.3 KiB
TypeScript

import { MessagePlugin } from "tdesign-vue-next";
import i18n from '@/i18n';
import { shouldRejectKnowledgeFileType } from "./fileTypeVerification";
// 声明全局运行时配置类型
declare global {
interface Window {
__RUNTIME_CONFIG__?: {
MAX_FILE_SIZE_MB?: number;
DEFAULT_LOCALE?: string;
};
}
}
// 从运行时配置获取最大文件大小(MB),支持 Docker 环境动态配置
// 优先级:运行时配置 > 构建时环境变量 > 默认值 50MB
export const MAX_FILE_SIZE_MB = window.__RUNTIME_CONFIG__?.MAX_FILE_SIZE_MB
|| Number(import.meta.env.VITE_MAX_FILE_SIZE_MB)
|| 50;
export const MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024;
export function generateRandomString(length: number) {
let result = "";
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
export function formatStringDate(date: any) {
let data = new Date(date);
let year = data.getFullYear();
let month = String(data.getMonth() + 1).padStart(2, '0');
let day = String(data.getDate()).padStart(2, '0');
let hour = String(data.getHours()).padStart(2, '0');
let minute = String(data.getMinutes()).padStart(2, '0');
let second = String(data.getSeconds()).padStart(2, '0');
return (
year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second
);
}
/** Returns true when the file exceeds the deploy-time upload limit. */
export function fileSizeVerification(file: Pick<File, 'size'>, silent = false) {
if (file.size <= MAX_FILE_SIZE_BYTES) return false;
if (!silent) {
MessagePlugin.error(i18n.global.t('error.fileSizeExceeded', { size: MAX_FILE_SIZE_MB }));
}
return true;
}
/**
* Returns true when the file should be **rejected**.
* @param validTypes - override the default extension whitelist with a dynamic set (e.g. from engine registry).
*/
export function kbFileTypeVerification(file: any, silent = false, validTypes?: Set<string> | string[]) {
if (shouldRejectKnowledgeFileType(file.name, validTypes)) {
if (!silent) {
MessagePlugin.error(i18n.global.t('error.unsupportedFileType'));
}
return true;
}
return fileSizeVerification(file, silent);
}