This commit is contained in:
ditiqi 2025-01-26 21:46:26 +08:00
parent a5552dba6b
commit 982b45bd63
6 changed files with 181 additions and 200 deletions

View File

@ -33,12 +33,13 @@ const AvatarUploader: React.FC<AvatarUploaderProps> = ({
}) => {
const { handleFileUpload, uploadProgress } = useTusUpload();
const [file, setFile] = useState<UploadingFile | null>(null);
const avatarRef = useRef<HTMLImageElement>(null);
const [previewUrl, setPreviewUrl] = useState<string>(value || "");
const [url, setUrl] = useState<string>(value || "");
const [uploading, setUploading] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
// 在组件中定义 key 状态
const [avatarKey, setAvatarKey] = useState(0);
const { token } = theme.useToken();
const handleChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
@ -77,7 +78,10 @@ const AvatarUploader: React.FC<AvatarUploaderProps> = ({
file?.fileKey
);
});
// await new Promise((resolve) => setTimeout(resolve, 5000)); // 方法1使用 await 暂停执行
// 使用 resolved 的最新值调用 onChange
// 强制刷新 Avatar 组件
setAvatarKey((prev) => prev + 1); // 修改 key 强制重新挂载
onChange?.(uploadedUrl);
message.success("头像上传成功");
} catch (error) {
@ -111,6 +115,8 @@ const AvatarUploader: React.FC<AvatarUploaderProps> = ({
/>
{previewUrl ? (
<Avatar
key={avatarKey}
ref={avatarRef}
src={previewUrl}
shape="square"
className="w-full h-full object-cover"

View File

@ -1,210 +1,186 @@
// TusUploader.tsx
import { useCallback, useState } from "react";
import {
useCallback,
useState,
useEffect,
forwardRef,
useImperativeHandle,
} from "react";
import {
UploadOutlined,
CheckCircleOutlined,
DeleteOutlined,
UploadOutlined,
CheckCircleOutlined,
DeleteOutlined,
} from "@ant-design/icons";
import { Upload, Progress, Button } from "antd";
import type { UploadFile } from "antd";
import { useTusUpload } from "@web/src/hooks/useTusUpload";
import toast from "react-hot-toast";
import { getCompressedImageUrl } from "@nice/utils";
export interface TusUploaderProps {
value?: string[];
onChange?: (value: string[]) => void;
}
export interface TusUploaderRef {
reset: () => void;
value?: string[];
onChange?: (value: string[]) => void;
}
interface UploadingFile {
name: string;
progress: number;
status: "uploading" | "done" | "error";
fileId?: string;
fileKey?: string;
name: string;
progress: number;
status: "uploading" | "done" | "error";
fileId?: string;
fileKey?: string;
}
export const TusUploader = forwardRef<TusUploaderRef, TusUploaderProps>(
({ value = [], onChange }, ref) => {
const { handleFileUpload, uploadProgress } = useTusUpload();
const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>(
[]
);
const [completedFiles, setCompletedFiles] = useState<UploadingFile[]>(
[]
);
export const TusUploader = ({ value = [], onChange }: TusUploaderProps) => {
const { handleFileUpload, uploadProgress } = useTusUpload();
const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>([]);
const [completedFiles, setCompletedFiles] = useState<UploadingFile[]>(
() =>
value?.map((fileId) => ({
name: `文件 ${fileId}`,
progress: 100,
status: "done" as const,
fileId,
})) || []
);
const [uploadResults, setUploadResults] = useState<string[]>(value || []);
// 同步父组件value到completedFiles
useEffect(() => {
setCompletedFiles(
value.map((fileId) => ({
name: `文件 ${fileId}`,
progress: 100,
status: "done" as const,
fileId,
}))
);
}, [value]);
const handleRemoveFile = useCallback(
(fileId: string) => {
setCompletedFiles((prev) => prev.filter((f) => f.fileId !== fileId));
setUploadResults((prev) => {
const newValue = prev.filter((id) => id !== fileId);
onChange?.(newValue);
return newValue;
});
},
[onChange]
);
// 暴露重置方法
useImperativeHandle(ref, () => ({
reset: () => {
setCompletedFiles([]);
setUploadingFiles([]);
},
}));
// 新增:处理删除上传中的失败文件
const handleRemoveUploadingFile = useCallback((fileKey: string) => {
setUploadingFiles((prev) => prev.filter((f) => f.fileKey !== fileKey));
}, []);
const handleRemoveFile = useCallback(
(fileId: string) => {
setCompletedFiles((prev) =>
prev.filter((f) => f.fileId !== fileId)
);
onChange?.(value.filter((id) => id !== fileId));
},
[onChange, value]
);
const handleBeforeUpload = useCallback(
(file: File) => {
const fileKey = `${file.name}-${Date.now()}`;
const handleRemoveUploadingFile = useCallback((fileKey: string) => {
setUploadingFiles((prev) =>
prev.filter((f) => f.fileKey !== fileKey)
);
}, []);
setUploadingFiles((prev) => [
...prev,
{
name: file.name,
progress: 0,
status: "uploading",
fileKey,
},
]);
const handleBeforeUpload = useCallback(
(file: File) => {
const fileKey = `${file.name}-${Date.now()}`;
handleFileUpload(
file,
(result) => {
setCompletedFiles((prev) => [
...prev,
{
name: file.name,
progress: 100,
status: "done",
fileId: result.fileId,
},
]);
setUploadingFiles((prev) => [
...prev,
{
name: file.name,
progress: 0,
status: "uploading",
fileKey,
},
]);
setUploadingFiles((prev) =>
prev.filter((f) => f.fileKey !== fileKey)
);
handleFileUpload(
file,
(result) => {
const newValue = [...value, result.fileId];
onChange?.(newValue);
setUploadingFiles((prev) =>
prev.filter((f) => f.fileKey !== fileKey)
);
},
(error) => {
console.error("上传错误:", error);
toast.error(
`上传失败: ${error instanceof Error ? error.message : "未知错误"}`
);
setUploadingFiles((prev) =>
prev.map((f) =>
f.fileKey === fileKey
? { ...f, status: "error" }
: f
)
);
},
fileKey
);
setUploadResults((prev) => {
const newValue = [...prev, result.fileId];
onChange?.(newValue);
return newValue;
});
},
(error) => {
console.error("上传错误:", error);
toast.error(
`上传失败: ${error instanceof Error ? error.message : "未知错误"}`
);
setUploadingFiles((prev) =>
prev.map((f) =>
f.fileKey === fileKey ? { ...f, status: "error" } : f
)
);
},
fileKey
);
return false;
},
[handleFileUpload, onChange, value]
);
return false;
},
[handleFileUpload, onChange]
);
return (
<div className="space-y-1">
<Upload.Dragger
name="files"
multiple
showUploadList={false}
style={{ background: "transparent", borderStyle: "none" }}
beforeUpload={handleBeforeUpload}>
<p className="ant-upload-drag-icon">
<UploadOutlined />
</p>
<p className="ant-upload-text">
</p>
<p className="ant-upload-hint"></p>
return (
<div className="space-y-1">
<Upload.Dragger
name="files"
multiple
showUploadList={false}
style={{ background: "transparent", borderStyle: "none" }}
beforeUpload={handleBeforeUpload}
>
<p className="ant-upload-drag-icon">
<UploadOutlined />
</p>
<p className="ant-upload-text"></p>
<p className="ant-upload-hint"></p>
<div className="px-2 py-0 rounded mt-1">
{uploadingFiles.map((file) => (
<div
key={file.fileKey}
className="flex flex-col gap-1 mb-2">
<div className="flex items-center gap-2">
<span className="text-sm">{file.name}</span>
</div>
<div className="flex items-center gap-2">
<Progress
percent={
file.status === "done"
? 100
: Math.round(
uploadProgress?.[
file.fileKey!
] || 0
)
}
status={
file.status === "error"
? "exception"
: "active"
}
className="flex-1"
/>
{file.status === "error" && (
<Button
type="text"
danger
icon={<DeleteOutlined />}
onClick={(e) => {
e.stopPropagation();
if (file.fileKey)
handleRemoveUploadingFile(
file.fileKey
);
}}
/>
)}
</div>
</div>
))}
<div className="px-2 py-0 rounded mt-1">
{uploadingFiles.map((file) => (
<div
key={file.fileKey}
className="flex flex-col gap-1 mb-2"
>
<div className="flex items-center gap-2">
<span className="text-sm">{file.name}</span>
</div>
<div className="flex items-center gap-2">
<Progress
percent={
file.status === "done"
? 100
: Math.round(uploadProgress?.[file.fileKey!] || 0)
}
status={file.status === "error" ? "exception" : "active"}
className="flex-1"
/>
{file.status === "error" && (
<Button
type="text"
danger
icon={<DeleteOutlined />}
onClick={(e) => {
e.stopPropagation();
if (file.fileKey) handleRemoveUploadingFile(file.fileKey);
}}
/>
)}
</div>
</div>
))}
{completedFiles.map((file) => (
<div
key={file.fileId}
className="flex items-center justify-between gap-2 mb-2">
<div className="flex items-center gap-2">
<CheckCircleOutlined className="text-green-500" />
<span className="text-sm">{file.name}</span>
</div>
<Button
type="text"
danger
icon={<DeleteOutlined />}
onClick={(e) => {
e.stopPropagation();
if (file.fileId)
handleRemoveFile(file.fileId);
}}
/>
</div>
))}
</div>
</Upload.Dragger>
</div>
);
}
);
{completedFiles.map((file) => (
<div
key={file.fileId}
className="flex items-center justify-between gap-2 mb-2"
>
<div className="flex items-center gap-2">
<CheckCircleOutlined className="text-green-500" />
<span className="text-sm">{file.name}</span>
</div>
<Button
type="text"
danger
icon={<DeleteOutlined />}
onClick={(e) => {
e.stopPropagation();
if (file.fileId) handleRemoveFile(file.fileId);
}}
/>
</div>
))}
</div>
</Upload.Dragger>
</div>
);
};

View File

@ -121,9 +121,7 @@ export default function StaffForm() {
<AvatarUploader
placeholder="点击上传头像"
className="rounded-lg"
onChange={(value) => {
console.log(value);
}}
style={{
width: "120px",
height: "150px",

View File

@ -34,6 +34,9 @@ export default function PostCommentCard({
layout>
<div className="flex items-start space-x-2 gap-2">
<div className="flex-shrink-0">
{/* <a href={post.author?.meta?.photoUrl}>
{post.author?.meta?.photoUrl}
</a> */}
<CustomAvatar
src={post.author?.meta?.photoUrl}
size={50}

View File

@ -19,7 +19,7 @@ export default function PostCommentEditor() {
const [signature, setSignature] = useState<string | undefined>(undefined);
const [fileIds, setFileIds] = useState<string[]>([]);
const { create } = usePost();
const uploaderRef = useRef<{ reset: () => void }>(null);
const [uploaderKey, setUploaderKey] = useState<number>(0);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
@ -48,9 +48,7 @@ export default function PostCommentEditor() {
toast.success("发布成功!");
setContent("");
setFileIds([]); // 重置上传组件状态
// if (uploaderRef.current) {
// uploaderRef.current.reset();
// }
setUploaderKey(uploaderKey + 1);
} catch (error) {
toast.error("发布失败,请稍后重试");
console.error("Error posting comment:", error);
@ -90,7 +88,7 @@ export default function PostCommentEditor() {
<TabPane tab="附件" key="2">
<div className="relative rounded-xl border border-white hover:ring-1 ring-white transition-all duration-300 ease-in-out bg-slate-100">
<TusUploader
ref={uploaderRef}
key={uploaderKey}
value={fileIds}
onChange={(value) => {
console.log("ids", value);

View File

@ -81,12 +81,12 @@ export function LetterBasicForm() {
<Form.Item name="resources" required={false}>
<div className="rounded-xl border border-white hover:ring-1 ring-white transition-all duration-300 ease-in-out bg-slate-100">
<TusUploader
onChange={(resources) =>
onChange={async (resources) => {
form.setFieldValue(
"resources",
resources
)
}
);
}}
/>
</div>
</Form.Item>