Browse Source

♻️ refactor(components): 优化文件上传相关组件代码

- 移除AvatarSelector和FileSelector组件中的uploadButtonText属性
- 移除MinioUploader组件中未使用的uploadingFiles状态管理
- 统一将文件ID参数从字符串转换为数字类型,确保API调用参数类型正确

🐛 fix(api): 修复文件详情获取和用户头像显示问题

- 修复文件ID参数类型错误,将toString()改为Number()确保正确的参数类型
- 修复MemberPage中用户头像显示路径错误,从user.avatar改为user.avatarFile?.fullUrl

♻️ refactor(pages): 优化FilesPage页面代码

- 简化handleUploadSuccess和handleUploadError回调函数参数
- 将搜索框的onKeyPress事件改为onKeyDown以支持更广泛的键盘事件
- 调整文件上传成功回调处理逻辑,移除未使用的参数
yourname 2 months ago
parent
commit
24df413ca1

+ 1 - 3
src/client/admin/components/AvatarSelector.tsx

@@ -19,7 +19,6 @@ interface AvatarSelectorProps {
   accept?: string;
   maxSize?: number;
   uploadPath?: string;
-  uploadButtonText?: string;
   previewSize?: 'small' | 'medium' | 'large';
   showPreview?: boolean;
   placeholder?: string;
@@ -31,7 +30,6 @@ const AvatarSelector: React.FC<AvatarSelectorProps> = ({
   accept = 'image/*',
   maxSize = 2,
   uploadPath = '/avatars',
-  uploadButtonText = '上传头像',
   previewSize = 'medium',
   showPreview = true,
   placeholder = '选择头像',
@@ -44,7 +42,7 @@ const AvatarSelector: React.FC<AvatarSelectorProps> = ({
     queryKey: ['file-detail', value],
     queryFn: async () => {
       if (!value) return null;
-      const response = await fileClient[':id']['$get']({ param: { id: value.toString() } });
+      const response = await fileClient[':id']['$get']({ param: { id: Number(value) } });
       if (response.status !== 200) throw new Error('获取文件详情失败');
       return response.json();
     },

+ 2 - 4
src/client/admin/components/FileSelector.tsx

@@ -18,7 +18,6 @@ export interface FileSelectorProps {
   accept?: string;
   maxSize?: number;
   uploadPath?: string;
-  uploadButtonText?: string;
   previewSize?: 'small' | 'medium' | 'large';
   showPreview?: boolean;
   placeholder?: string;
@@ -34,7 +33,6 @@ export const FileSelector: React.FC<FileSelectorProps> = ({
   accept = '*/*',
   maxSize = 10,
   uploadPath = '/files',
-  uploadButtonText = '上传文件',
   previewSize = 'medium',
   showPreview = true,
   placeholder = '选择文件',
@@ -60,7 +58,7 @@ export const FileSelector: React.FC<FileSelectorProps> = ({
         // 批量获取多个文件详情
         const filePromises = value.map(async (fileId) => {
           try {
-            const response = await fileClient[':id']['$get']({ param: { id: fileId.toString() } });
+            const response = await fileClient[':id']['$get']({ param: { id: Number(fileId) } });
             if (response.status === 200) {
               return response.json();
             }
@@ -77,7 +75,7 @@ export const FileSelector: React.FC<FileSelectorProps> = ({
       
       // 处理单选模式下的单值
       if (!Array.isArray(value)) {
-        const response = await fileClient[':id']['$get']({ param: { id: value.toString() } });
+        const response = await fileClient[':id']['$get']({ param: { id: Number(value) } });
         if (response.status !== 200) throw new Error('获取文件详情失败');
         return [await response.json()];
       }

+ 0 - 13
src/client/admin/components/MinioUploader.tsx

@@ -64,7 +64,6 @@ const MinioUploader: React.FC<MinioUploaderProps> = ({
   displayMode = 'full'
 }) => {
   const [fileList, setFileList] = useState<UploadFile[]>([]);
-  const [uploadingFiles, setUploadingFiles] = useState<Set<string>>(new Set());
   const [dragActive, setDragActive] = useState(false);
 
   // 根据尺寸模式获取样式配置
@@ -142,11 +141,6 @@ const MinioUploader: React.FC<MinioUploaderProps> = ({
       })
     );
     
-    setUploadingFiles(prev => {
-      const newSet = new Set(prev);
-      newSet.delete(uid);
-      return newSet;
-    });
     
     // toast.success(`文件 "${file.name}" 上传成功`);
     onUploadSuccess?.(result.fileKey, result.fileUrl, file);
@@ -168,11 +162,6 @@ const MinioUploader: React.FC<MinioUploaderProps> = ({
       })
     );
     
-    setUploadingFiles(prev => {
-      const newSet = new Set(prev);
-      newSet.delete(uid);
-      return newSet;
-    });
     
     // toast.error(`文件 "${file.name}" 上传失败: ${error.message}`);
     onUploadError?.(error, file);
@@ -195,8 +184,6 @@ const MinioUploader: React.FC<MinioUploaderProps> = ({
       }
     ]);
     
-    // 添加到上传中集合
-    setUploadingFiles(prev => new Set(prev).add(uid));
     
     try {
       // 验证文件大小

+ 7 - 7
src/client/admin/pages/Files.tsx

@@ -64,7 +64,7 @@ export const FilesPage: React.FC = () => {
   // 更新文件记录
   const updateFile = useMutation({
     mutationFn: ({ id, data }: { id: number; data: UpdateFileRequest }) =>
-      fileClient[':id'].$put({ param: { id: id.toString() }, json: data }),
+      fileClient[':id'].$put({ param: { id: Number(id) }, json: data }),
     onSuccess: () => {
       toast.success('文件记录更新成功');
       queryClient.invalidateQueries({ queryKey: ['files'] });
@@ -78,7 +78,7 @@ export const FilesPage: React.FC = () => {
 
   // 删除文件记录
   const deleteFile = useMutation({
-    mutationFn: (id: number) => fileClient[':id'].$delete({ param: { id: id.toString() } }),
+    mutationFn: (id: number) => fileClient[':id'].$delete({ param: { id: Number(id) } }),
     onSuccess: () => {
       toast.success('文件记录删除成功');
       queryClient.invalidateQueries({ queryKey: ['files'] });
@@ -114,13 +114,13 @@ export const FilesPage: React.FC = () => {
   };
 
   // 处理上传成功回调
-  const handleUploadSuccess = (fileKey: string, fileUrl: string, file: File) => {
+  const handleUploadSuccess = () => {
     toast.success('文件上传成功');
     queryClient.invalidateQueries({ queryKey: ['files'] });
   };
 
   // 处理上传失败回调
-  const handleUploadError = (error: Error, file: File) => {
+  const handleUploadError = (error: Error) => {
     toast.error(`上传失败: ${error instanceof Error ? error.message : '未知错误'}`);
   };
 
@@ -206,7 +206,7 @@ export const FilesPage: React.FC = () => {
                 placeholder="搜索文件名称或类型"
                 value={searchText}
                 onChange={(e) => setSearchText(e.target.value)}
-                onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
+                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                 className="max-w-sm"
               />
             </div>
@@ -377,8 +377,8 @@ export const FilesPage: React.FC = () => {
               uploadPath="/files"
               maxSize={500}
               multiple={false}
-              onUploadSuccess={(fileKey, fileUrl, file) => {
-                handleUploadSuccess(fileKey, fileUrl, file);
+              onUploadSuccess={() => {
+                handleUploadSuccess();
                 setIsUploadModalOpen(false);
               }}
               onUploadError={handleUploadError}

+ 2 - 2
src/client/home/pages/MemberPage.tsx

@@ -50,8 +50,8 @@ const MemberPage: React.FC = () => {
             <CardContent className="pt-6">
               <div className="flex flex-col items-center space-y-4">
                 <Avatar className="h-24 w-24">
-                  <AvatarImage 
-                    src={user.avatar || `https://avatar.vercel.sh/${user.username}`} 
+                  <AvatarImage
+                    src={user.avatarFile?.fullUrl || `https://avatar.vercel.sh/${user.username}`}
                     alt={user.nickname || user.username}
                   />
                   <AvatarFallback className="text-2xl bg-primary text-primary-foreground">