后端返回图片流前端展示图片

根据后端返回的图片流格式,选用合适方法转换
下面以base64为例

if(res.status == 200) {
     res.data.data.forEach((item,index) => {
        let Array = 'data:image/png;base64,' + item
        let blob = this.base64toBlob(Array)
        let url = URL.createObjectURL(blob)
        this.imageList.push({
             name:this.keyList[index],
             src:url
        })
   });
}

下面是图片流的两种转换方式:

arrayBufferToBase64(buffer) {
   var binary = ''
   var bytes = new Uint8Array(buffer)
   var len = bytes.byteLength
   for (var i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i])
   }
   return window.btoa(binary)
},
base64toBlob(dataurl) {
   var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
   bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
   while (n--) {
     u8arr[n] = bstr.charCodeAt(n);
   }
   return new Blob([u8arr], { type: mime });
},

你可能感兴趣的:(前端,前端,javascript,开发语言)