doctor-mail/apps/web/src/hooks/useTusUpload.ts

59 lines
1.3 KiB
TypeScript
Raw Normal View History

2025-01-22 23:19:51 +08:00
// useTusUpload.ts
import { useState } from "react";
import * as tus from "tus-js-client";
interface UploadResult {
url?: string;
}
export function useTusUpload() {
const [progress, setProgress] = useState(0);
const [isUploading, setIsUploading] = useState(false);
const [uploadError, setUploadError] = useState<string | null>(null);
const handleFileUpload = (
file: File,
onSuccess: (result: UploadResult) => void,
onError: (error: Error) => void
) => {
setIsUploading(true);
setProgress(0);
setUploadError(null);
const upload = new tus.Upload(file, {
endpoint: "http://localhost:3000/upload", // 替换为实际的上传端点
retryDelays: [0, 1000, 3000, 5000],
metadata: {
filename: file.name,
filetype: file.type,
},
onProgress: (bytesUploaded, bytesTotal) => {
const uploadProgress = (
(bytesUploaded / bytesTotal) *
100
).toFixed(2);
setProgress(Number(uploadProgress));
},
onSuccess: () => {
setIsUploading(false);
setProgress(100);
onSuccess({ url: upload.url });
},
onError: (error) => {
setIsUploading(false);
setUploadError(error.message);
onError(error);
},
});
upload.start();
};
return {
progress,
isUploading,
uploadError,
handleFileUpload,
};
}