Files
mini-programs/src/services/uploadFiles.ts
2026-02-14 12:59:21 +08:00

129 lines
3.2 KiB
TypeScript

import Taro from '@tarojs/taro'
import envConfig from '@/config/env'
import { API_CONFIG } from '@/config/api'
import httpService from './httpService'
import tokenManager from '../utils/tokenManager'
// 用户接口
export interface UploadFilesData {
id: string,
filePath: string,
description?: string,
tags?: string,
is_public?: 0 | 1,
}
export interface uploadFileResponse {
code: number,
message: string,
data: uploadFileResponseData,
}
export interface uploadFileResponseData {
id: number,
user_id: number,
file_name: string,
original_name: string,
file_path: string,
file_url: string,
file_size: number,
resource_type: string,
mime_type: string,
description: string,
tags: string[],
is_public: string,
view_count: number,
download_count: number,
created_at: string,
updated_at: string,
}
// 从上传错误中取出可展示的文案
function get_upload_error_msg(error: any): string {
if (!error) return "上传失败";
const msg =
error?.message ||
(typeof error?.error === "string" ? error.error : error?.error?.message) ||
(error?.data?.message ?? error?.data?.msg) ||
"";
return (msg && String(msg).trim()) || "上传失败";
}
// 发布球局类
class UploadApi {
async upload(req: UploadFilesData): Promise<{ id: string, data: uploadFileResponseData }> {
const fullUrl = `${envConfig.apiBaseURL}/api/gallery/upload`;
const authHeader = tokenManager.getAuthHeader();
const { id, ...rest } = req;
try {
const res = await Taro.uploadFile({
url: fullUrl,
filePath: rest.filePath,
name: "file",
formData: {
description: rest.description,
tags: rest.tags,
is_public: rest.is_public,
},
header: authHeader,
});
const parsed = JSON.parse(res.data);
if (parsed.code !== 0) {
const msg = get_upload_error_msg(parsed);
Taro.showToast({ title: msg, icon: "none" });
throw new Error(msg);
}
return { id, data: parsed.data };
} catch (error) {
const msg = get_upload_error_msg(error);
Taro.showToast({ title: msg, icon: "none" });
throw { id, error };
}
}
async batchUpload(req: UploadFilesData[]): Promise<{ id: string, data: uploadFileResponseData | null }[]> {
return Promise.all(req.map(async (item) => {
try {
const res = await this.upload(item);
return res;
} catch (error) {
return { id: item.id, data: null }
}
}))
}
// 上传单张图片到OSS
async upload_oss_img(file_path: string): Promise<any> {
try {
let fullUrl = `${envConfig.apiBaseURL}/api${API_CONFIG.UPLOAD.OSS_IMG}`
const authHeader = tokenManager.getAuthHeader()
const response = await Taro.uploadFile({
url: fullUrl,
filePath: file_path,
name: 'file',
header: authHeader,
});
const result = JSON.parse(response.data);
if (result.code === 0) {
return result.data;
} else {
throw new Error(result.message || '上传失败');
}
} catch (error) {
console.warn('上传图片失败:', error);
throw error;
}
}
}
// 导出认证服务实例
export default new UploadApi()