uni-app 实现后端返回的图片文件流转base64

使用uni-app开发webapp,由于后端返回的图片文件是二进制文件流形式,前端展示需要转换格式,首先想到的就是转成base64进行展示,话不多说,直接填坑。

使用uni-app的uni.request进行网络请求,在网上查找的资料是如果返回的是文件流需要设置responseType为‘bold’类型,uni-app官网文档描述:设置响应的数据类型。合法值:text、arraybuffer。

故需要设置responseType为arraybuffer类型。

return request({
        method: "GET", // 请求方式
          url: platFormUrl+'/downFile.do', // 请求url
           responseType:'arraybuffer',
           data: data // 参数
        })

请求拿到数据之后转换成blod对象,blod对象转base64

let blob = new Blob([res],{type: 'image/png'})

  this.blobToDataURL(blob,(res)=>{
    console.log(res)
  })

blod对象转base64方法

blobToDataURL(blob, callback) {
   let a = new FileReader();
   a.onload = function(e) {
      callback(e.target.result);
   }
   a.readAsDataURL(blob);
}

 

posted @ 2021-01-19 10:05  凌晨肆点的洛杉矶  阅读(5517)  评论(0编辑  收藏  举报