antd 表单验证图片必传

表单验证图片必传

import React, {Component} from 'react';
import {Form, Upload, Button, Icon, message} from 'antd';

const FormClass = Form.create()(
  class extends Component {
    constructor(props) {
      super(props);
      this.state = {
        imageUrl: '',
      };
    }

    // 图片上传前
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
      }
      return isJpgOrPng && isLt2M;
    }

    // 图片上传成功,并改变。
    handleChange = (info) => {
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        this.getBase64(info.file.originFileObj, imageUrl =>
          this.setState({
            imageUrl,
          }),
        );
      }
    };

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

    // 表单提交
    handleSubmit = (e) => {
      e.preventDefault();
      this.props.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values);
        }
      });
    }

    render() {
      const {getFieldDecorator} = this.props.form;
      const uploadButton = (
        <div>
          <Icon type={'plus'} />
          <div className="ant-upload-text">Upload</div>
        </div>
      );
      return (
        <Form
          className="login-form"
          onSubmit={this.handleSubmit}
        >
          <Form.Item>
            {getFieldDecorator('imageUrl', {
              rules: [{required: true, message: '请上传图片!'}],
            })(
              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                // action="https://www.mocky.io/v2/5cc8019d300000980a055e76" // antd接口
                action={`${libConfig.parsePath}/api/public/upload`} // 后端接口
                beforeUpload={this.beforeUpload}
                onChange={this.handleChange}
              >
                {this.state.imageUrl ? <img src={this.state.imageUrl} alt="avatar" style={{width: '100%'}} /> : uploadButton}
              </Upload>
            )}
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">提交</Button>
          </Form.Item>
        </Form>
      );
    }
  }
);

export default FormClass;

 

posted @ 2020-11-27 11:49  本溢  阅读(1093)  评论(0)    收藏  举报