Files
jinshen-website/server/utils/file.ts
R2m1liA a520775a8d
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m2s
refactor: 将文件请求由app端转到server端
2025-11-12 18:19:21 +08:00

54 lines
1.4 KiB
TypeScript

/**
* 判断文件是否支持预览
*/
export function isPreviewable(mime: string | null | undefined): boolean {
if (!mime || mime === undefined) return false;
return (
mime.startsWith('image/') ||
mime.startsWith('video/') ||
mime === 'application/pdf' ||
mime.startsWith('text/')
);
}
/**
* 从 Directus 获取文件元信息
*/
export async function getFileMeta(id: string): Promise<FileMeta | null> {
const runtimeConfig = useRuntimeConfig();
const baseUrl = runtimeConfig.public.directus.url;
const access_token = runtimeConfig.public.directus.token;
try {
const response = await $fetch<{ data: DirectusFile }>(
`${baseUrl}/files/${id}`,
{
headers: {
Authorization: access_token ? `Bearer ${access_token}` : '',
},
}
);
const file = response.data;
if (!file) return null;
return {
id: file.id,
title: file.filename_disk ?? '',
filename_download: file.filename_download ?? '',
type: file.type ?? '',
filesize: Number(file.filesize),
width: file.width ?? undefined,
height: file.height ?? undefined,
uploaded_on: file.uploaded_on ?? undefined,
url: `/api/assets/${file.id}`,
previewable: isPreviewable(file.type),
};
} catch (error) {
if (error instanceof Error) {
logger.error('Error fetching file metadata:', error.message);
}
return null;
}
}