react.js 如何完成多张图片转码Base64 组件

1.新增一个子组件文件:ToBase64Img.js

import React, { Component } from 'react';
import { Modal } from 'antd';
import fetch from 'dva/fetch';
import { object2formdata } from '@/utils/utils';
import domain from '@/utils/domain-config';
class ToBase64Img extends React.Component {
  state = {
    visible: false,
    bigImg: '',
    base64Path: '',
    pathCache: {}
  };

  handleImgEnlarge(imgPath) {
    this.setState({
      bigImg: imgPath,
      visible: true
    })
  };

  handleOk () {
    this.setState({
      bigImg: '',
      visible: false
    })
  }

  handleOpenImg(img) {
    window.open(img);
  }

  async getImg(urlStr) {
    const { base64Path, pathCache } = this.state;
    if (base64Path && pathCache[urlStr] && pathCache[urlStr] == base64Path) return
    if (pathCache[urlStr]) {
      this.setState({
        base64Path: pathCache[urlStr]
      })
      return
    }

    let url = `${domain}/manage/img/admin/getImg`

    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      credentials: 'include',
      mode:'cors',
      cache:'default',
      body: `urlStr=${urlStr}`
    }).then((res) => res.json()).then((res) => {
      pathCache[urlStr] = `data:image/png;base64,${res.data}`
      this.setState({
        base64Path: `data:image/png;base64,${res.data}`,
        pathCache
      })
    })
  }

  render() {
    const { imgPath } = this.props
    const { bigImg, base64Path } = this.state
    this.getImg(imgPath)
    return (
      <div>
        <img
          src={base64Path}
          style={{ height: '70px', marginRight: '10px' }}
          onClick={() => this.handleImgEnlarge(imgPath)}
        />
        <Modal
          title="查看图片"
          visible={this.state.visible}
          onCancel={this.handleOk.bind(this)}
          onOk={this.handleOk.bind(this)}
          style={{ position: 'relative' }}
        >
          <div style={{ width: '400px', marginLeft: '35px' }}>
            <img src={bigImg} style={{ width: '400px' }} onClick={() => this.handleOpenImg(bigImg)} />
          </div>
        </Modal>
      </div>
    )
  }
}
export default ToBase64Img;

2.在父组件引入

import ToBase64Img from '@/components/ToBase64Img';

3.调用

 <ToBase64Img imgPath={img} {...this.props} />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值