antd react 文件上传只允许上传一个文件且上传后隐藏上传按钮
- 效果图
- 代码解析
效果图
代码解析
import { Form, Upload, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useState, useEffect } from 'react';
import { BASE_URL } from '@/utils/request';
const FormItemInputUpload = (props) => {const [visble, setVisibel] = useState(false); //用于图判断图标是否显示useEffect(() => {if (props) {setVisibel(false); //防止上传图片后取消,重置数据后,上传图标和图片都不显示}}, [props]);const normFile = (e) => {// 上传判断,有文件则隐藏上传图标,否则显示if (e.fileList.length == 0) {setVisibel(false);} else {setVisibel(true);}if (Array.isArray(e)) {return e;}return e?.fileList;};const onRemove = (e) => {// 因为antd本身缺陷,我们上传成功后,再次删除后,系统会默认为已经上传,导致不为空验证失效。//所以我们图片移除后同时改变表单值const urls = [props.form.getFieldValue(props.name)].flat().filter((item) => item != e.response.data[0].imageAddress);props.form.setFieldsValue({[props.name]: urls,});};return (<Form.Itemlabel={props.label}name={props.name}valuePropName="fileList"getValueFromEvent={normFile}rules={// 必填验证,rules是组件传入的值,有则必填 props?.rules && [{required: true,validator: (_, value, callback) => {if (!value || value.length == 0) {callback(`请上传${props.label}`);} else {callback();}},},]}><UploadmaxCount={props?.maxCount || 1}action={`${BASE_URL}/cdsj-file/upload`}name="files"headers={{ Authorization: localStorage.getItem('token') }}listType="picture-card"accept=".png,.jpeg,.jpg"beforeUpload={(file) => {const isPNG =file.type == 'image/png' ||file.type == 'image/jpg' ||file.type == 'image/jpeg';if (!isPNG) {message.error('请上传图片格式文件!');}return isPNG || Upload.LIST_IGNORE;}}onRemove={onRemove}>{visble ? null : <PlusOutlined />}</Upload></Form.Item>);
};export default FormItemInputUpload;