弃用 btoa 转用 blob吧

当后端返回图片文件流的时候,需要展示预览图片。

const  yourApi =  ()=> request({
  url:`api/getStream`,
method:get,
catchAll:true,
responseType:"arraybuffer"
})


yourApi(params).then(res => { item.imgBase64 = `data:image/png;base64,${btoa( new Uint8Array(res).reduce( (data, byte) => data + String.fromCharCode(byte), '' ) )}` })

当使用btoa 时候,会警告你此函数是为了旧版本Web APi兼容,不应再新代码使用,对于使用Node.js 环境,应使用Buffer.from(str,'base64')和 buf.toString('base64')执行base64编码字符和二进制数据之间的转换。

当我们使用Blob,时候,responseType既可以用arraybuffer 也可以使用blob。

   const getCaptcha = () => {
      getCaptchaApi().then(res => {
        console.log(res);
        const blob = new Blob([res.data]);
        imgUrl.value = window.URL.createObjectURL(blob);
      })
    }

Bolb 的作用大概如下

1:大文件切片上传。

2:从互联网下载数据,可以是pdf,excel,图片等等

3:Blob 可以用作图片 ,超链接的URL 

  <img  src="blob:http://localhost:8080/60eac02b-e2ae-402a-a2ac-6e12e12e003b" />

posted on 2022-06-29 10:36  冰love  阅读(960)  评论(0编辑  收藏  举报

导航