表单中使用antd组件库的上传组件的文件(图片)上传、预览、删除。删除由组件自带,本篇主要讲解上传和预览功能。
1、这里使用了react的useState,定义了初始化变量
const [fileList, setFileLists] = useState([]);
const [previewVisible, setPreviewVisible] = useState(false);
const [previewImage, setPreviewImage] = useState(false);
2、表单中使用上传组件的参数getValueFromEvent所传的事件
// 上传文件前的文件大小判断
const normFile = (e) => {
let size = 0;
if (Array.isArray(e)) {
size = e[0].size;
} else if (e.fileList.length > 0) {
size = e.fileList[0].size;
}
const isLt5M = size / 1024 / 1024 <= 5;
if (!isLt5M) {
setFileLists([]);
Modal.error({
title: '文件大小不能超过5M',
});
return [];
}
if (Array.isArray(e)) {
return e;
}
setFileLists(e.fileList);
return e && e.fileList;
};
3、显示和关闭预览图片弹出框
// 图片预览
const handlePreview = async (file) => {
setPreviewImage(file.thumbUrl || file.preview);
setPreviewVisible(true);
};
// 关闭预览弹出框页面
const handleCancel = () => setPreviewVisible(false);
4、这是编辑页面时,回显数据所调用的方法,如无该操作,可忽略
// 回显页面数据 enterInvoiceDetail ,图片显示
// 获取图片的url
const getFileUrlFunc = async () => {
const params = {
fileCode: enterInvoiceDetail.invoice_file,
};
if (!Array.isArray(enterInvoiceDetail.invoice_file)) {
const url = await getFileUrl(params);
const arr = [
{
thumbUrl: url,
uid: 'rc-upload-1603332043321-2',
name: '图1.jpg',
status: 'done',
},
];
setFileLists(arr);
setFieldsValue({ file: arr });
} else {
setFileLists(enterInvoiceDetail.invoice_file);
setFieldsValue({ file: enterInvoiceDetail.invoice_file });
}
};
5、组件的使用
const uploadButton = (
<div>
<Icon type="plus" />
{/* <div className="ant-upload-text">Upload</div> */}
</div>
);
<FormItem label="附件">
{getFieldDecorator('file', {
valuePropName: 'fileList',
getValueFromEvent: normFile,
rules: [{ required: true, message: '请上传附件' }],
})(
<Upload
action="/file/upload" // 接口的上传路径
method="POST"
listType="picture-card"
accept=".jpeg,.jpg,.png,.pdf,image/jpeg,image/jpg,image/png,application/pdf" // 允许上传的文件格式
onPreview={handlePreview}
>
{fileList?.length >= 1 ? null : uploadButton}
</Upload>,
)}
<div>支持格式:png/jpg/jpeg/pdf,文件大小不超过5M</div>
<Modal visible={previewVisible} footer={null} onCancel={handleCancel}>
<img alt="example" style={{ width: '100%' }} src={previewImage} />
</Modal>
</FormItem>
6、效果图
- 鼠标悬浮在图片上
- 预览图