| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- import { authService } from './authService';
- const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
- export interface OSSUploadResponse {
- url: string;
- filename: string;
- size: number;
- }
- export interface ApiResponse<T> {
- code: number;
- message: string;
- data: T;
- }
- class OSSApiService {
- private baseUrl = `${API_BASE_URL}/api/oss`;
- async uploadFile(file: File, prefix: string = 'uploads'): Promise<ApiResponse<OSSUploadResponse>> {
- const formData = new FormData();
- formData.append('file', file);
- const authHeader = authService.getAuthHeader();
- if (!authHeader) {
- throw new Error('未授权:请先登录');
- }
- const response = await fetch(`${this.baseUrl}/upload?prefix=${encodeURIComponent(prefix)}`, {
- method: 'POST',
- headers: { 'Authorization': authHeader },
- body: formData,
- });
- if (!response.ok) {
- if (response.status === 401) {
- authService.logout();
- throw new Error('未授权:请先登录');
- }
- throw new Error(`上传失败: ${response.status}`);
- }
- return response.json();
- }
- }
- export const ossApi = new OSSApiService();
- /**
- * 上传文件到 OSS(带进度回调)
- * @param file 要上传的文件
- * @param prefix OSS 路径前缀
- * @param onProgress 进度回调函数 (0-100)
- * @returns 文件 URL
- */
- export async function uploadFile(
- file: File,
- prefix: string = 'uploads',
- onProgress?: (percent: number) => void
- ): Promise<string> {
- const formData = new FormData();
- formData.append('file', file);
- const authHeader = authService.getAuthHeader();
- if (!authHeader) {
- throw new Error('未授权:请先登录');
- }
- return new Promise((resolve, reject) => {
- const xhr = new XMLHttpRequest();
- // 监听上传进度
- xhr.upload.addEventListener('progress', (e) => {
- if (e.lengthComputable && onProgress) {
- const percent = Math.round((e.loaded / e.total) * 100);
- onProgress(percent);
- }
- });
- // 监听完成
- xhr.addEventListener('load', () => {
- if (xhr.status === 200) {
- try {
- const response: ApiResponse<OSSUploadResponse> = JSON.parse(xhr.responseText);
- if (response.code === 200 && response.data) {
- resolve(response.data.url);
- } else {
- reject(new Error(response.message || '上传失败'));
- }
- } catch (error) {
- reject(new Error('解析响应失败'));
- }
- } else if (xhr.status === 401) {
- authService.logout();
- reject(new Error('未授权:请先登录'));
- } else {
- reject(new Error(`上传失败: ${xhr.status}`));
- }
- });
- // 监听错误
- xhr.addEventListener('error', () => {
- reject(new Error('网络错误'));
- });
- xhr.addEventListener('abort', () => {
- reject(new Error('上传已取消'));
- });
- // 发送请求
- xhr.open('POST', `${API_BASE_URL}/api/oss/upload?prefix=${encodeURIComponent(prefix)}`);
- xhr.setRequestHeader('Authorization', authHeader);
- xhr.send(formData);
- });
- }
|