From 1b506edfbf6a9e33fdfe7a31a8a5b85e093c4f66 Mon Sep 17 00:00:00 2001 From: Chever John Date: Tue, 30 Jun 2026 16:27:17 +0800 Subject: [PATCH] feat: use authenticated upload API in ImageUploader - Add uploadFile function to commonApi with Authorization header - Replace raw fetch with commonApi.uploadFile in ImageUploader Co-Authored-By: Claude --- src/api/common.ts | 31 ++++++++++++++++++++++++++++++- src/components/ImageUploader.tsx | 22 ++-------------------- 2 files changed, 32 insertions(+), 21 deletions(-) diff --git a/src/api/common.ts b/src/api/common.ts index ac5d549..fafd917 100644 --- a/src/api/common.ts +++ b/src/api/common.ts @@ -1,4 +1,4 @@ -import { http } from './client'; +import { http, getAccessToken } from './client'; import type { Company, CompanyMember, Profile } from '../types'; interface Notification { @@ -46,4 +46,33 @@ export const commonApi = { submitFeedback: (data: { content: string }) => http.post('/common/feedback', data), + + uploadFile: async (file: File, bucket: string, pathPrefix: string): Promise => { + const formData = new FormData(); + formData.append('file', file); + formData.append('bucket', bucket); + formData.append('path_prefix', pathPrefix); + + const token = getAccessToken(); + const headers: Record = {}; + if (token) headers['Authorization'] = `Bearer ${token}`; + + const res = await fetch('/api/v1/common/upload', { + method: 'POST', + headers, + body: formData, + credentials: 'include', + }); + + if (!res.ok) { + throw new Error('upload failed'); + } + + const json = await res.json(); + if (json.code !== 0) { + throw new Error(json.message || 'upload failed'); + } + + return json.data?.url || ''; + }, }; diff --git a/src/components/ImageUploader.tsx b/src/components/ImageUploader.tsx index ea7f68f..64fc2c6 100644 --- a/src/components/ImageUploader.tsx +++ b/src/components/ImageUploader.tsx @@ -1,7 +1,7 @@ import React, { useRef, useState } from 'react'; import { motion } from 'framer-motion'; import { Camera, X, Upload, ImageIcon } from 'lucide-react'; -import { http } from '../api'; +import { commonApi } from '../api/common'; export type UploadBucket = 'avatars' | 'product_images'; @@ -68,25 +68,7 @@ export function ImageUploader({ setUploading(true); try { - const formDataObj = new FormData(); - formDataObj.append('file', file); - formDataObj.append('bucket', bucket); - formDataObj.append('path_prefix', pathPrefix); - - // TODO: 文件上传接口待后端实现,当前使用 fetch 直接发送 FormData - const res = await fetch('/api/v1/common/upload', { - method: 'POST', - body: formDataObj, - }); - - if (!res.ok) { - alert('图片上传失败'); - setUploading(false); - return; - } - - const json = await res.json(); - const publicUrl = json.data?.url || ''; + const publicUrl = await commonApi.uploadFile(file, bucket, pathPrefix); setPreviewUrl(publicUrl); onChange(publicUrl); setUploading(false);