关于antd上传限制只能上传图片

看别人的代码也是好的
多学习嘛

以下两种方法antd上传限制只能上传图片

用 getValueFromEvent: this.normFile,控制

<FormItem {...formItemLayout} label="客房图片" colon={false}>
              <div className="clearfix">
                {getFieldDecorator('pic',
                  {
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue: info && info.img_path,
                  })(

                    <Upload
                      accept="image/*"
                      action="/admin/Media/upLoad"
                      headers={{authorization: getAdminInfo()}}
                      listType="picture-card"
                      onPreview={this.handlePreview}
                      onChange={this.handleChange}
                  >
                      <div>
                        <Icon type="plus" />
                        <div className="ant-upload-text">Upload</div>
                      </div>
                    </Upload>,
                )}
                <Modal visible={previewVisible} footer={null} onCancel={this.picCancel}>
                  <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
              </div>
            </FormItem>
 normFile = (e) => {
    // 检查图片类型
    // 只能上传三种图片格式
    const isJPG = e.file.type === 'image/jpeg';
    const isPNG = e.file.type === 'image/png';
    const isBMP = e.file.type === 'image/bmp';
    const isGIF = e.file.type === 'image/gif';
    const isWEBP = e.file.type === 'image/webp';
    const isPic = isJPG || isPNG || isBMP || isGIF || isWEBP;
    if (!isPic) {
      message.error('只能上传图片');
      console.log(e.fileList);
      return e.fileList.filter((fileItem)=> e.file.uid !== fileItem.uid);
    } else {
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    }
  };
  picCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }

  handleChange = ({fileList}) => {
    this.setState({
      fileList,
    } )
  };

方法2 用 fileList: […fileListD],控制

<FormItem
              label="  "
              {...formItemLayout}
              wrapperCol={{ span: 18 }}
              colon={false}
            >
              <div style={{ height: "100%" }}>
                <Upload
                  accept="image/*"
                  name="pic"
                  listType="picture-card"
                  {...uploadProp}
                  onPreview={this.handlePreview}
                  onChange={this.handleChange}
                  beforeUpload={this.beforeUpload}
                >
                  {fileList.length >= 5 ? null : uploadButton}
                </Upload>
                <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                  <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
              </div>
            </FormItem>
const uploadProp = {
      fileList: [...fileListD],
      action: '/hq/home/Media/upLoad.hq',
      // headers: {
      //   authorization: window.localStorage.getItem(STORAGETOKENKEY),
      // },
    };
 // 图片上传
  handleCancel = () => this.setState({ previewVisible: false });
  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };
  handleChange = ({ fileList }) => {
    const img_id = [];
    if (fileList[fileList.length - 1]) {
      if (fileList[fileList.length - 1].status === 'done') {
        for (let i = 0; i < fileList.length; i++) {
          img_id.push(fileList[i].response.info.id);
        }
      }
    }

    for (let i = 0; i < fileList.length; i++) {
      const file = fileList[i];
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isBMP = file.type === 'image/bmp';
      const isGIF = file.type === 'image/gif';
      const isWEBP = file.type === 'image/webp';
      const isPic = isJPG || isPNG || isBMP || isGIF || isWEBP;

      if (!isPic) {
        fileList = fileList.filter((fileItem)=> file.uid !== fileItem.uid);
      }
    }
    pic = img_id.toString();
    fileListD = fileList;
    this.setState({
      fileList,
    });
  };

  beforeUpload=(file, fileList) => {
    // 检查图片类型
    // 只能上传三种图片格式
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    const isBMP = file.type === 'image/bmp';
    const isGIF = file.type === 'image/gif';
    const isWEBP = file.type === 'image/webp';
    const isPic = isJPG || isPNG || isBMP || isGIF || isWEBP;
    if (!isPic) {
      message.error('只能上传图片');
      this.setState({
        fileListD: fileList.filter((fileItem)=> file.uid !== fileItem.uid),
      });
      return false;
    }
    return isPic;
  };
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Ant Design 的 Upload 组件来实现图片上传功能。首先,需要安装 Ant Design: ``` npm install antd ``` 然后,在你的 React 组件中引入 Upload 组件: ```jsx import { Upload, message } from 'antd'; import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'; class Avatar extends React.Component { state = { loading: false, imageUrl: '' }; handleChange = info => { if (info.file.status === 'uploading') { this.setState({ loading: true }); return; } if (info.file.status === 'done') { // Get this url from response in real world. getBase64(info.file.originFileObj, imageUrl => this.setState({ imageUrl, loading: false, }), ); } }; render() { const { loading, imageUrl } = this.state; const uploadButton = ( <div> {loading ? <LoadingOutlined /> : <PlusOutlined />} <div className="ant-upload-text">Upload</div> </div> ); return ( <Upload name="avatar" listType="picture-card" className="avatar-uploader" showUploadList={false} action="https://www.mocky.io/v2/5cc8019d300000980a055e76" beforeUpload={beforeUpload} onChange={this.handleChange} > {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton} </Upload> ); } } ``` 这个例子中,我们定义了一个 Avatar 组件,其中包含一个 Upload 组件。我们设置了 Upload 组件的 name、listType、className、showUploadList、action、beforeUpload 和 onChange 属性。其中: - name 表示上传文件的参数名; - listType 表示上传列表的样式,这里设置为 picture-card; - className 表示 Upload 组件的类名; - showUploadList 表示是否显示上传列表; - action 表示上传的 URL; - beforeUpload 是一个函数,用于上传前的校验; - onChange 是一个函数,用于上传后的处理。 在 handleChange 函数中,我们根据上传文件的状态来处理上传结果,并将图片的 base64 编码保存到 state 中。最后,我们将图片显示出来,如果没有上传图片,则显示上传按钮。 在 beforeUpload 函数中,我们可以进行上传前的校验。例如,限制上传图片的大小和类型: ```jsx function 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; } ``` 这个例子中,我们限制上传图片的类型为 JPG 和 PNG,大小不超过 2MB。 最后,需要引入 message、LoadingOutlined 和 PlusOutlined 组件: ```jsx import { Upload, message } from 'antd'; import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'; ``` 这样,就可以使用 Ant Design 的 Upload 组件实现图片上传功能了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值