import React, { useState } from 'react'; import { useTusUpload } from '../hooks/useTusUpload'; interface FileDownloadProps { fileId?: string; fileName?: string; className?: string; } export function FileDownload({ fileId, fileName, className }: FileDownloadProps) { const { getFileUrlByFileId, getFileInfo } = useTusUpload(); const [inputFileId, setInputFileId] = useState(fileId || ''); const [fileInfo, setFileInfo] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); // 获取文件信息 const handleGetFileInfo = async () => { if (!inputFileId.trim()) { setError('请输入文件ID'); return; } setLoading(true); setError(null); try { const info = await getFileInfo(inputFileId); if (info) { setFileInfo(info); } else { setError('文件不存在或未准备好'); } } catch (err) { setError('获取文件信息失败'); } finally { setLoading(false); } }; // 直接下载文件 const handleDirectDownload = () => { const downloadUrl = getFileUrlByFileId(inputFileId); window.open(downloadUrl, '_blank'); }; // 复制下载链接 const handleCopyLink = async () => { const downloadUrl = getFileUrlByFileId(inputFileId); try { await navigator.clipboard.writeText(downloadUrl); alert('下载链接已复制到剪贴板!'); } catch (error) { console.error('复制失败:', error); } }; // 在新窗口预览文件 const handlePreview = () => { const downloadUrl = getFileUrlByFileId(inputFileId); window.open(downloadUrl, '_blank'); }; return (

文件下载

{/* 文件ID输入 */}
setInputFileId(e.target.value)} placeholder="输入文件ID" className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" />
{/* 错误信息 */} {error &&
{error}
} {/* 文件信息 */} {fileInfo && (

文件信息

文件名: {fileInfo.title || '未知'}

类型: {fileInfo.type || '未知'}

状态: {fileInfo.status || '未知'}

{fileInfo.meta?.size && (

大小: {formatFileSize(fileInfo.meta.size)}

)}

创建时间: {new Date(fileInfo.createdAt).toLocaleString()}

)} {/* 操作按钮 */} {inputFileId && (
)} {/* 使用说明 */}

使用说明:

  • • 输入文件ID后点击"查询"获取文件信息
  • • "直接下载"会打开新窗口下载文件
  • • "预览/查看"适用于图片、PDF等可预览的文件
  • • "复制链接"将下载地址复制到剪贴板
); } // 格式化文件大小 function formatFileSize(bytes: number): string { if (bytes === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; }