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

本文主要是基于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群:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_37617413/article/details/106334643
今日推荐