upload的典型demo
import React from 'react';
import { Upload, Button, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
const beforeUpload = (file: File) => {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('只能上传 JPG/PNG 文件!');
return Upload.LIST_IGNORE;
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('图片必须小于2MB!');
return Upload.LIST_IGNORE;
}
return true;
};
const customRequest = async (options: any) => {
const { file, onSuccess, onError, onProgress } = options;
const formData = new FormData();
formData.append('file', file);
try {
// 模拟上传进度
onProgress({ percent: 50 });
// 这里用 fetch 模拟上传
await new Promise((resolve) => setTimeout(resolve, 1000));
// 假设上传成功
onSuccess('ok');
message.success('上传成功');
} catch (err) {
onError(err);
message.error('上传失败');
}
};
function index() {
return (
<div>
<Upload
beforeUpload={beforeUpload}
customRequest={customRequest}
showUploadList={false}
>
<Button icon={<UploadOutlined />}>点击上传图片</Button>
</Upload>
</div>
);
}
export default index;
漫思
浙公网安备 33010602011771号