前端: 添加文件上传弹窗组件

This commit is contained in:
Frontend Developer 2026-03-10 08:33:23 +00:00
parent 9ee28f404f
commit 2192c8d636

View File

@ -0,0 +1,91 @@
import React, { useState } from 'react';
import { Modal, Upload, Button, Progress, message } from 'antd';
import { UploadOutlined, InboxOutlined } from '@ant-design/icons';
const { Dragger } = Upload;
function UploadModal({ visible, onClose, onSuccess }) {
const [uploading, setUploading] = useState(false);
const [progress, setProgress] = useState(0);
const [fileList, setFileList] = useState([]);
const handleUpload = async ({ file, onProgress }) => {
setUploading(true);
const formData = new FormData();
formData.append('file', file);
try {
const token = localStorage.getItem('token');
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', (e) => {
if (e.lengthComputable) {
const percent = Math.round((e.loaded / e.total) * 100);
setProgress(percent);
onProgress({ percent });
}
});
xhr.open('POST', '/api/files/upload');
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
xhr.onload = () => {
if (xhr.status === 200) {
message.success('上传成功');
onSuccess?.();
setUploading(false);
setProgress(0);
setFileList([]);
onClose();
} else {
message.error('上传失败');
setUploading(false);
}
};
xhr.onerror = () => {
message.error('上传失败');
setUploading(false);
};
xhr.send(formData);
} catch (error) {
message.error('上传失败: ' + error.message);
setUploading(false);
}
};
return (
<Modal
title="上传文件"
open={visible}
onCancel={onClose}
footer={null}
width={500}
>
<Dragger
name="file"
multiple={true}
customRequest={handleUpload}
fileList={fileList}
onChange={({ fileList }) => setFileList(fileList)}
disabled={uploading}
>
<p className="ant-upload-drag-icon">
<InboxOutlined />
</p>
<p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
<p className="ant-upload-hint">
支持单个或批量上传严禁上传恶意文件
</p>
</Dragger>
{uploading && (
<Progress percent={progress} status="active" style={{ marginTop: '16px' }} />
)}
</Modal>
);
}
export default UploadModal;