遇到的问题:

在vue项目中请求axios接口,后端返回的图片是二进制流数据,如果直接在img标签下的src中使用是没有用的。怎么样将图片流显示在页面中呢?

解决方法:

(一)、response-type为blob类型

a. 把response-type改为blob类型

b. 在请求后端接口返回data时,调用window的URL方法。

//完整代码
<img :src="imgUrl " />

axios.get('url',{
   params:{
       key:this.key
   },
   responseType: 'blob',   //这里是声明期望返回的数据类型,为blob
}).then(response => {  
   this.imgUrl = window.URL.createObjectURL(res.data);   //这里调用window的URL方法
})

(二)、response-type为arraybuffer类型

a. 把response-type改为arraybuffer类型

b. 在请求后端接口返回data时,将其转为base64。

axios.get('url',{
    params:{
        a: this.a         
    },
    responseType: 'arraybuffer'   //这里是声明期望返回的数据类型,为arraybuffer
}).then(response => {    
    //这里的data数据是后台返回来的,byte是params中的键值
    const bufferUrl = btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
    this.imgUrl = 'data:image/png;base64,' + bufferUrl;
})


Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐