[react] antd Upload 组件 笔记

何时使用

上传是将信息(网页、文字、图片、视频等)通过网页或者上传工具发布到远程服务器上的过程

  • 当需要上传一个或一些文件时。

  • 当需要展现上传的进度时。

  • 当需要使用拖拽交互时。

引--antd官网 https://ant.design/components/upload-cn/

  

 <Upload
                                                className="pic"
                                                accept="image/jpeg,image/png"
                                                listType="picture-card"
                                                fileList={fileList}
                                                beforeUpload={(e) => this.beforeUpload(e, "twoPath")}
                                                onChange={(e) => this.onChangePic(e, "twoPath", "twoFlag")}
                                            >
                                                    {this.state.twoPath ?
                                                        <div>
                                                            <img src={this.state.twoPath} style={{  "100%", height: "100%" }}></img>
                                                            {/* <span className="up change" style={{ display: (baseParms.Info && baseParms.Info.qualificationPhoto && this.state.twoPath != "" ? "none" : "inline-block") }}>上传照片</span> */}
                                                            <span className="change" style={{ display: ((baseParms.Info && baseParms.Info.qualificationPhoto) || this.state.twoPath != "" ? "inline-block" : "none") }}>重新上传</span>
                                                        </div>
                                                        : uploadButton}
                                                </Upload>

  

 1.本地照片上传-更换显示是通过通过本地文件地址拿到图片路径然后转为base64----------getBase64

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

2.可限制图片的格式 和 大小 --------beforeUpload

 beforeUpload = (file, name) => {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                message.error('只能上传JPG/PNG文件!');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.error('图片大小不能超过2MB!');
            }
            return false;
        }

 3.设置回显---地址赋值 imageUrl

 onChangePic = (info, name, flag) => {
            // console.log("info", info)
            this.getBase64(info.file, imageUrl =>
                this.setState({
                    [name]: imageUrl,
                    // loading: false,
                    // fileList: info.file,
                }, () => {
                    // console.log("imageUrl-0-000----",imageUrl)
                }),

            );

  

原文地址:https://www.cnblogs.com/522040-m/p/12917400.html