|
13 | 13 | * See the License for the specific language governing permissions and |
14 | 14 | * limitations under the License. |
15 | 15 | */ |
| 16 | +import axios from 'axios'; |
| 17 | +import {ApiResponse} from "@/services/common.ts"; |
16 | 18 |
|
17 | 19 | /** |
18 | 20 | * 业务API服务 |
19 | 21 | * 封装所有业务相关的API调用 |
20 | 22 | */ |
21 | 23 |
|
22 | | -interface UploadResponse { |
23 | | - success: boolean; |
24 | | - message?: string; |
25 | | - url?: string; |
| 24 | +interface FileStorage { |
| 25 | + id: number; |
| 26 | + filePath?: string; |
| 27 | + url: string; |
| 28 | + filename?: string; |
26 | 29 | } |
27 | 30 |
|
| 31 | +export type FileUploadResult = ApiResponse<FileStorage>; |
| 32 | + |
28 | 33 | // 文件上传API |
29 | 34 | export const fileUploadApi = { |
30 | 35 | // 上传头像 |
31 | | - uploadAvatar(file: File): Promise<UploadResponse> { |
| 36 | + async uploadAvatar(file: File): Promise<FileStorage | null> { |
32 | 37 | const formData = new FormData(); |
33 | 38 | formData.append('file', file); |
34 | | - |
35 | 39 | const url = '/api/upload/avatar'; |
36 | | - return fetch(url, { |
37 | | - method: 'POST', |
38 | | - body: formData, |
39 | | - }).then(async response => { |
40 | | - if (!response.ok) { |
41 | | - const text = await response.text().catch(() => ''); |
42 | | - throw new Error(`Upload failed: ${response.status} ${text}`); |
| 40 | + try { |
| 41 | + const response = await axios.post<FileUploadResult>(url, formData, { |
| 42 | + headers: { |
| 43 | + 'Content-Type': 'multipart/form-data' |
| 44 | + } |
| 45 | + }); |
| 46 | + if (response.data.success) { |
| 47 | + return response.data.data ?? null; |
43 | 48 | } |
44 | | - const ct = response.headers.get('content-type') || ''; |
45 | | - if (ct.includes('application/json')) { |
46 | | - return await response.json(); |
| 49 | + throw new Error(response.data.message); |
| 50 | + } catch (error) { |
| 51 | + if (axios.isAxiosError(error) && error.response?.status === 404) { |
| 52 | + return null; |
47 | 53 | } |
48 | | - const text = await response.text(); |
49 | | - return { success: true, message: 'ok', url: text }; |
50 | | - }); |
| 54 | + throw error; |
| 55 | + } |
51 | 56 | }, |
52 | 57 | }; |
0 commit comments