import React, { useState } from 'react'; import { Button, TextField, Box, Typography, Alert, } from '@mui/material'; import { Download } from '@mui/icons-material'; interface S3DownloadButtonProps { label?: string; } const S3DownloadButton: React.FC = ({ label = 'S3下载' }) => { const [fileName, setFileName] = useState(''); const [error, setError] = useState(''); const [success, setSuccess] = useState(''); const handleDownload = async () => { if (!fileName.trim()) { setError('请输入文件名'); return; } try { setError(''); setSuccess(''); // 构建S3文件URL const fileUrl = `http://172.14.3.142:4566/my-bucket/uploads/${fileName.trim()}`; // 方法1:直接使用a标签下载(如果S3配置了正确的Content-Disposition) const link = document.createElement('a'); link.href = fileUrl; link.download = fileName.trim(); link.target = '_blank'; // 方法2:如果方法1不行,尝试添加时间戳避免缓存问题 // const timestamp = new Date().getTime(); // const downloadUrl = `${fileUrl}?t=${timestamp}`; // link.href = downloadUrl; // 添加到DOM并触发点击 document.body.appendChild(link); link.click(); document.body.removeChild(link); setSuccess(`文件 ${fileName} 下载成功!`); setFileName(''); } catch (err) { setError(`下载失败: ${err instanceof Error ? err.message : '未知错误'}`); } }; const handleKeyPress = (event: React.KeyboardEvent) => { if (event.key === 'Enter') { handleDownload(); } }; return ( S3文件下载 setFileName(e.target.value)} onKeyPress={handleKeyPress} placeholder="例如: 20251125_150429_f43f9a67.txt" sx={{ minWidth: 300 }} /> {error && ( setError('')}> {error} )} {success && ( setSuccess('')}> {success} )} 提示:输入文件名后点击下载按钮,文件将从S3存储桶下载到本地 ); }; export default S3DownloadButton;