Vue后端返回图片,前端显示

Vue后端返回图片,前端显示

首先我们明确两个点:

  1. 普通请求接收的时候是json格式,图片流的接收模式可选两种:blob和arraybuffer。
  2. blob和arraybuffer本质上都是二进制数据。
    1. 如果使用blob我们只需要用 window.URL.createObjectURL(res)就可以得到图片链接;
    2. 如果使用arraybuffer,我们需要将其转为base64的格式。
<div class="getCaptcha" @click="getimgCaptcha()">
        <img
          :src="codeImg"
          style="width:135px;height:40px;"
          alt="点击重新获取验证码"
          >
</div>

1. blob

请求设置,代码如下:

export function getCaptcha () {
  return request({
    url: /getCaptcha,
    method: 'get',
    responseType: 'blob' //选择接收方式为blob
 
  })
}

图片处理,代码如下:

getCaptcha (e) {
    getCaptcha().then(res => {
     this.codeImg = window.URL.createObjectURL(res) // 这里调用window的URL方法
      console.log(this.codeImg, '地址')
    })
    .catch(err => {
     console.log(err)
    })
  },

2. arraybuffer

请求设置,代码如下:

// 图片验证码
export function getCaptcha () {
  return request({
    url: /getCaptch,
    method: 'get',
    responseType: 'arraybuffer'
 
  })
}

图片处理,代码如下:

getCaptcha (e) {
    getCaptcha().then(res => {
   //1. btoa表示 base64转ASCII ,对应的还有 atob 表示 ASCII转base64
   //2. Unit8Arrat() 是arraybuffer里面的一种类型
   const url = 'data:image/png;base64,' + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))
      this.codeImg = url
      console.log(this.codeImg, '地址')
    })
    .catch(err => {
     console.log(err)
    })
  },
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值