基于react antDesign 封装一个校验图片尺寸与大小的图片上传组件

本文介绍了一个基于React和AntDesign的图片上传组件,该组件能够校验图片的尺寸和大小,确保上传的图片符合预设的标准。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文主要是基于react antDesign UpLoad组件,封装一个可以校验尺寸、大小的图片上传组件。

Ant Design官方文档已经给出了校验图片大小的demo,代码如下。

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;
}

官方文档中限制的2M,file.size取到的是字节,做了转换file.size / 1024 / 1024,这里对这个参数进行了优化,改为从props里面获取,在beforeUpload方法里面做了如下更新:

 	let maxSize = this.props.maxSize;
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }

    let _limitSize = true;
    console.log('====>img fileSize', file.size)
    // maxSize 这里的maxSize 单位为KB,file.size单位为字节,需要转换下
    if (maxSize) {
      _limitSize = file.size < maxSize * 1024;
    }

添加图片宽高的校验逻辑,这边定义一个名为isSize的方法。首先将beforeUpload里面获取到的文件信息当参数传入到isSize()中。可分为以下几步:
一、新建图片元素 img = new Image();
二、图片加载完,获取图片元素宽高;
三、校验宽高,返回校验结果;

isSize = (file: { name: string }) => {
    let self = this;
    return new Promise((resolve, reject) => {
      let width = this.props.width;
      let height = this.props.height;
      let _URL = window.URL || window.webkitURL;
      let img = new Image();
      img.onload = function () {
        let valid = false;
        console.log('=====>img width', img.width)
        console.log('=====>img height', img.height)

        valid = img.width == width && img.height == height;

        if (!valid) {
          message.error(file.name + ' 图片尺寸不符合要求,请修改后重新上传!');
        }
        self.setState({
          _errorSize: !valid,
        });
      };
      img.src = _URL.createObjectURL(file);
    });
  };
实现图片上传组件代码如下:
/*
 * @Date 2020/5/11
 * @Author zuolinya
 * @Description 图片上传
 *
 */
import React from 'react';
import { Upload, message, Button } from 'antd';
import Urls from '@/utils/urls';
import { baseURL } from "@/utils/requestAxios"

import './index.less';

function getBase64(
  img: Blob,
  callback: { (imageUrl: any): void; (arg0: string | ArrayBuffer | null): any },
) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

interface UploadImgType {
  width?: number;
  height?: number;
  maxSize?: number;
  onUploadSuccess: Function; //图片上传成功之后的回跳
  defaultValue?: any;
}

class UploadImg extends React.Component<UploadImgType, any> {
  static defaultProps = {
    current: 0,
  };
  state = {
    loading: false,
    imageUrl: '',
    _errorSize: false,
    _errorMax: false,
    widthOriginal: '',
    heightOriginal: '',
  };

  handleChange = (info: any) => {
    let self = this;
    if (info.file.status === 'uploading') {
      self.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, (imageUrl: any) => {
        if (!(self.state._errorSize || self.state._errorMax)) {
          self.setState({
            imageUrl: imageUrl,
          });
          // 将图片信息回调给父组件
          self.props.onUploadSuccess(info.file);
        }
        self.setState({
          loading: false,
        });
      });
    }
  };

  beforeUpload = (file: { type: string; size: number }) => {
    let maxSize = this.props.maxSize;
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }

    let _limitSize = true;
    console.log('====>img fileSize', file.size)
    // maxSize 这里的maxSize 单位为KB,file.size单位为字节,需要转换下
    if (maxSize) {
      _limitSize = file.size < maxSize * 1024;
    }
    if (!_limitSize) {
      message.error(`图片超过最大尺寸限制 ${maxSize}KB!`);
      this.setState({
        _errorMax: true,
      });
    } else {
      this.setState({
        _errorMax: false,
      })
    }
    if (this.props.width || this.props.height) {
      this.isSize(file);
    }


    this.setState({
      _errorSize: this.state._errorSize && isJpgOrPng,
    });
  };

  isSize = (file: { name: string }) => {
    let self = this;

    return new Promise((resolve, reject) => {
      let width = this.props.width;
      let height = this.props.height;
      let _URL = window.URL || window.webkitURL;
      let img = new Image();
      img.onload = function () {
        let valid = false;
        console.log('=====>img width', img.width)
        console.log('=====>img height', img.height)

        valid = img.width == width && img.height == height;

        if (!valid) {
          message.error(file.name + ' 图片尺寸不符合要求,请修改后重新上传!');
        }
        self.setState({
          _errorSize: !valid,
        });
      };
      img.src = _URL.createObjectURL(file);
    });
  };

  render() {
    const uploadButton = (
      <div>
        <div className="ant-upload-text">
          <Button>{this.state.loading ? '上传中' : '上传'}		       </Button>
        </div>
      </div>
    );
    let { imageUrl: _imageUrl } = this.state;
    _imageUrl = _imageUrl || this.props.defaultValue;
    return (
      <Upload
        accept="image/png, image/jpeg"
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        withCredentials
        // action为你的上传地址,这里是项目引入地址,可忽略
        action={baseURL + Urls.fetchUploadImage}
        beforeUpload={this.beforeUpload}
        onChange={this.handleChange}
      >
        {_imageUrl ? <img src={_imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
      </Upload>
    );
  }
}

export default UploadImg;

如有问题请联系我~

欢迎加入QQ群:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值