1
import React from 'react';

import { Upload } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';

const Supload = ({ type = "image",imageUrl="", fn }) => {
    let loading = false;
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div className="ant-upload-text">Upload</div>
        </div>
    );
    function getBase64(img, callback) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    };
    function handleChange(info) {
        console.log(info);
        if (info.file.status === 'uploading') {
           loading=false;
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, image =>{
                if(info.file.response.code==200){
                    fn(info.file.response.data.file_path)
                }
            });
        }
    };
    return (
        <div >
            <Upload
                name="content"
                data={{
                    type: type
                }}
                listType="picture-card"
                headers={
                    { Authorization: 'Bearer ' + localStorage.getItem('Bearer') }
                }
                showUploadList={false}
                onChange={handleChange}
                action="/api/uploadFile"
            >
                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
            </Upload>
        </div>
    );
};

export default Supload;

data里面的数据是上传时额外传的数据,可根据自己需要修改,也可以不要
headers里面的数据是添加了身份验证,我这个项目的身份验证就是这样的
因为这是个函数式组件,所以如果需要重新渲染页面,需要父组件更新子组件属性的值。
父组件中:

                                        <Supload imageUrl={imageUrl} fn={this.uploadSuccess}/>

下面这个是子组件触发的父组件事件

uploadSuccess=(data)=>{
        console.log(data)
        this.setState({
            imageUrl:data
        })
    };

子组件上传成功后,触发该事件,父组件更新imageUrl的值,触发子组件更新


弱鸡的前端程序员
33 声望3 粉丝