上传图片Upload

参考:antd upload组件使用_ERRFTF的博客-CSDN博客

antd upload实例和一些解决问题的办法_热爱前端的小君同学的博客-CSDN博客

  const [states, setStates] = useState<{
    loading: boolean;
    imageUrl: string | undefined;
  }>({
    loading: false,
    imageUrl: ''
  });

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

组件的Upload的使用:

里面的属性

beforeUpload:这个属性就是上传的类型限制

//这个beforeUpload属性是限制类型,固定写法
const beforeUpload = (file:any) => {
        console.log('file', file);
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJPG) {
            message.error('只能上传JPG或PNG格式的图片文件!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJPG && isLt2M;
       }

customRequest: 作为自定义上传的方法与后端进行交互并可以传递额外的参数

  const posterUploadFile = async (options: any) => {
    // 创建一个空对象实例
    const uploadData = new FormData();
    // 调用append()方法来添加数据
    uploadData.append('file', options.file);
    uploadData.append('bizKey', type ? 'media' : 'news');
    const res: any = await uploadImage(uploadData);
    if (res) {
      onChange?.(res.filePath);
      setStates((states) => ({ ...states, loading: false, imageUrl: res.filePath || '' }));
    } else {
      message.error('长传失败');
      setStates((states) => ({ ...states, loading: false }));
    }
  };

onchange:方法可以通过上传的状态对文件进行一些判断

     handleChange = async(info) => {
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
           await this.getBase64(info.file.originFileObj, imageUrl =>
            this.setState({
              imageUrl,
              loading: false,
              fileList:info.fileList,
            }), 
            );
        }
      };
或者 
const handleChange = (info: UploadChangeParam<UploadFile<any>>) => {
    if (info.file.status === 'uploading') {
      setStates((states) => ({ ...states, loading: true }));
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (imageUrl: string) => {
        setStates({
          imageUrl,
          loading: false
        });
      });
    }
  };

组件

 <Upload
              disabled={disabled}
              onChange={handleChange}
              listType="picture-card"
              beforeUpload={beforeUpload}
              showUploadList={false}
              className={classNames({ 'avatar-uploader': !type })}
              customRequest={posterUploadFile}
            >
              <img />
            </Upload>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值