Based on react antDesign, encapsulate an image upload component that verifies the size and size of images.

This article is mainly based on react antDesign UpLoadcomponents, encapsulating an image upload component that can verify size and size.

The official Ant Design documentation has given a demo for verifying the image size . The code is as follows.

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

The limit of 2M in the official document file.sizeis obtained by bytes and converted file.size / 1024 / 1024. This parameter is optimized here and is propsobtained from it instead. beforeUploadThe following updates are made in the method:

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

Add the verification logic of the image width and height, and define a isSizemethod named here. First, beforeUploadpass the file information obtained inside as parameters isSize(). It can be divided into the following steps:
1. Create a new image element img = new Image();
2. After the image is loaded, obtain the width and height of the image element;
3. Verify the width and height and return the verification result;

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);
    });
  };
The code to implement the image upload component is as follows:
/*
 * @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;

If you have any questions, please contact me~

Welcome to join QQ group:

Insert image description here

Guess you like

Origin blog.csdn.net/qq_37617413/article/details/106334643