vue3中图片链接地址转base64方法


const imgToBase64 = (imgUrl: string): Promise<string> => {
  return new Promise(resolve => {
    window.URL = window.URL || window.webkitURL

    // 创建 XMLHttpRequest 对象
    const xhr = new XMLHttpRequest()

    // get请求,请求图片资源
    xhr.open('get', imgUrl, true)
    xhr.responseType = 'blob'
    xhr.onload = function () {
      if (this.status === 200) {
        // 返回结果是 Blob 类型
        const blob = this.response

        // 读取文件内容
        const reader = new FileReader()

        reader.onloadend = function () {
          // 将 DataURL 作为返回值 resolve
          resolve(reader.result as string)
        }

        // 将 Blob 文件编码成 Base64
        reader.readAsDataURL(blob)
      }
    }

    xhr.send()
  })
}

请求示例:

 imgToBase64(res.data.options.project_contract_official_seal_url)
      .then(base64 => {
        console.log(base64) // 在这里处理 base64 字符串
        officialSeal.value = base64
      })
      .catch(error => {
        console.error(error) // 处理错误
      })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值