This commit is contained in:
2025-07-16 11:06:09 +08:00
parent 1bb34b4932
commit b8b86598d8
2 changed files with 110 additions and 71 deletions

View File

@@ -161,4 +161,35 @@ class RequestCancelManager {
// 导出单例实例
export const requestDeduplicator = new RequestDeduplicator();
export const requestCancelManager = new RequestCancelManager();
export const requestCancelManager = new RequestCancelManager();
/**
* 通用文件上传方法(支持图片、文件)
* @param {File} file - 要上传的文件对象
* @param {string} [uploadUrl='/v1/attachment/upload'] - 上传接口地址
* @returns {Promise<string>} - 上传成功后返回文件url
*/
export async function uploadFile(file: File, uploadUrl: string = '/v1/attachment/upload'): Promise<string> {
const formData = new FormData();
formData.append('file', file);
const token = typeof window !== 'undefined' ? localStorage.getItem('token') : '';
const headers: Record<string, string> = {};
if (token) headers['Authorization'] = `Bearer ${token}`;
try {
const response = await fetch(uploadUrl, {
method: 'POST',
headers,
body: formData,
});
const res = await response.json();
if (res?.url) {
return res.url;
}
if (res?.data?.url) {
return res.data.url;
}
throw new Error(res?.msg || '文件上传失败');
} catch (e: any) {
throw new Error(e?.message || '文件上传失败');
}
}