Antd Design Pro 图片上传组件

页面中的使用

<Col span={24} className={styles.logo}>
    <Form.Item
        name="projectLogo"
        label="Logo"
        rules={[
            {
                required: false,
            },
        ]}
        className={styles.label}>
        <Upload defaultLogo={props.location.query.projectLogo}/>
                                    
    </Form.Item>
</Col>

Upload.jsx

import React, {
    useEffect, 
    useState
} from 'react';
// import styles from './UploadComponent2.less';
import {tenantId} from '@/utils/accountCenter.js';
import {getFileUrl} from '@/utils/file.js';
import {
    // Menu, Row, Col, Carousel, Popover, Button, 
    Upload, message, Modal
    // Select, Space, Form,Input 
} from 'antd';
import styles from './Upload.less';
import {
    // UserOutlined,
    // PlusCircleFilled,
    // PictureFilled,
    // EnvironmentFilled,
    // RightOutlined,
    // CloseCircleFilled,
    // MenuFoldOutlined,
    // CopyOutlined,
    // AppstoreFilled,
    LoadingOutlined,
    PlusOutlined,
    // MinusCircleOutlined,
} from '@ant-design/icons';
// import MenuCenter from './MenuCenter';
// import HeadPortrait from './HeadPortrait'
// const { Option } = Select;

const index = (props) => {


    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState(props.defaultLogo);
    const [previewVisible, setPreviewVisible] = useState(false);
    const [fileList, setfileList] = useState([]);
    const [isOk, setIsOk] = useState(0);
    useEffect(() => {
        // debugger
        if(props.defaultLogo){
            setImageUrl(getFileUrl()+props.defaultLogo);
            // debugger
            setfileList([{
                // uid: '-1',
                name: 'image.png',
                status: 'done',
                thumbUrl: getFileUrl()+props.defaultLogo,
                url: getFileUrl()+props.defaultLogo,
            }])
        }
        // debugger
    }, []);

    function getBase64(img, callback) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }

    function beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        setIsOk(1);
        if (!isJpgOrPng) {
            message.error('你只能上传JPG/PNG文件!');
            setIsOk(0);
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            setIsOk(0);
            message.error('文件大小不能大于2MB!');
        }

   
        return isJpgOrPng && isLt2M;
    }

    function handleChangeFile(info) {
        // debugger
        if (info.file.status === 'uploading') {
            // this.setState({ loading: true });
            setLoading(true);
            // props.onChange(info);
            // return;
        }
        if (info.file.status === 'done') {
            // debugger
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, imageUrl => {
                setLoading(false);
                setImageUrl(imageUrl);
                props.onChange(info);
            });
            
        }

        if(!isOk){
            return;
        }
        // console.log(info)
        setfileList(info.fileList)
    };

    const uploadButton = (
        <div style={{ color: '#999' }}>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>上传</div>
            <div>照片</div>
        </div>
    );

    // const onPreview = async file => {
    //     // let src = file.url;
    //     // if (!src) {
    //     //     src = await new Promise(resolve => {
    //     //         const reader = new FileReader();
    //     //         reader.readAsDataURL(file.originFileObj);
    //     //         reader.onload = () => resolve(reader.result);
    //     //     });
    //     // }
    //     // const image = new Image();
    //     // image.src = src;
    //     // const imgWindow = window.open(src);
    //     // imgWindow.document.write(image.outerHTML);
    //     setPreviewVisible(true);
    // };

    // const getExtraData = () => {
    //     return {
    //         fileDirPath: '/private/reply/',
    //         registrationCode: '73f9ae9aaea2',
    //     };
    // };
    const uploadParams = {
        fileDirPath: '/private/project/',
        registrationCode: tenantId,
    };

    const onRemove =  async file =>{
        console.log(file)
        setImageUrl('')
        setfileList(file.fileList)
        props.onChange(file);
    };

    const handleCancel = () => {
        setPreviewVisible(false);
    }

   // debugger
    return (
        <div
        className={styles.upload}
        // style={{display: 'flex'}}
        >
            <span>
            <Upload
                name="file"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={true}
                action="/api/file/upload"
                beforeUpload={beforeUpload}
                onChange={handleChangeFile}
                data={uploadParams}
              //  onPreview={onPreview}
              //fileList={fileList?fileList:[]}
                onRemove={onRemove}
                maxCount="1"
                fileList={fileList}
            >
                
                {
                    imageUrl ?
                         //<img src={imageUrl} alt="example" style={{ width: '100%', height: '100%' }} /> 
                        // <div style={{
                        //     width: '100%',
                        //     height: '100%',
                        //     backgroundImage: 'url(' + imageUrl + ')',
                        //     backgroundSize: '100% 100%',
                        //     color: '#fff',
                        //     display: 'flex',
                        //     alignItems: 'center',
                        //     justifyContent: 'center',
                        //     borderTopLeftRadius: 4,
                        //     borderTopRightRadius: 4,
                        // }}>更换图片</div>
                        null: uploadButton}
            </Upload>

            <Modal
                    visible={previewVisible}
                    title={'图片'}
                    footer={null}
                    onCancel={handleCancel}
                    >
                        <img alt="图片" style={{width: '100%'}} src={imageUrl}></img>
            </Modal>
                    
            </span>
            
            <span className={styles.span}>支持上传png、jpg格式的照片<br/>
                建议尺寸120 x 120 px。
            </span>
        </div>
    )
};
export default index;

Upload.less

.span {
    font-size: 12px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #666666;
    display: inline-block;
    // vertical-align:middle;
    align-self:center;
}

.ant-upload-picture-card-wrapper {
    display: inline-block;
    width: 40%;
}

.upload {
    display: flex;
    flex-wrap: nowrap;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值