import CropperImg from '@/components/CropperImg'; import { useOss } from '@/Hook/useOss'; import { PlusOutlined } from '@ant-design/icons'; import { message, Upload } from 'antd'; import { RcFile } from 'antd/es/upload'; import dayjs from 'dayjs'; import React, { useEffect, useState } from 'react'; import styles from './index.less'; type CompareType = '<' | '<=' | '>' | '>=' | '=' | '!='; interface Props { type?: any; value?: string; onChange?: (data: { value: string; file: RcFile; name: string }) => void; size?: { width: number; height: number; evalW: CompareType; evalH: CompareType; msg: string }; // 是否裁剪 isCropper?: boolean; isEdit?: boolean; } const UploadImg: React.FC = ({ value, onChange, size, type, isCropper, isEdit }) => { /********************************/ const [visible, setVisible] = useState(false); const [file, setFile] = useState(); const ossUpload = useOss(true); const [imageUrl, setImageUrl] = useState(''); /********************************/ useEffect(() => { setImageUrl(value || ''); }, [value]); const uploadButton = (
{' '}
上传图片 {size?.width} * {size?.height}
); const upload = (file: RcFile) => { let name = dayjs().valueOf().toString(); ossUpload.run(file, name).then((res: any) => { if (res?.data) { let [fileName, nameSuffix] = file.name.split('.'); onChange?.(res.data.url); } }); }; return ( <> {}} className={imageUrl ? styles.upLoadTrue : ''} beforeUpload={(file: RcFile): any => { if (file.size > 10485760) { message.error('图片大小大于10M,请压缩在上传'); return; } let img: any = new Image(); let _URL = window.URL || window.webkitURL; img.onload = function (e: any) { if ( (size?.width && eval(`${this.width} ${size.evalW} ${size?.width}`)) || (size?.height && eval(`${this.height} ${size?.evalH} ${size?.height}`)) ) { if ( isCropper && ((isEdit && eval(`${this.width} >= ${size?.width}`) && eval(`${this.height} >= ${size?.height}`)) || !isEdit) ) { setFile(file); setVisible(true); } else { message.error( `传入的图片大小不符, 上传图片宽度${this.width}高度${this.height}, ${size?.msg}`, ); } return; } upload(file); }; img.src = _URL.createObjectURL(file); }} > {imageUrl ? avatar : uploadButton} {/* 裁剪 */} {visible && ( setVisible(false)} file={file} onChange={(fileList: any[], file: any) => { upload(file); setVisible(false); }} /> )} ); }; export default React.memo(UploadImg);