问题:在vue中处理后台返回的图片流,并将图片流显示在页面中,如何解决?
遇到的问题:在vue项目中请求axios接口,后端返回的图片是二进制流数据,如果直接在img标签下的src中使用是没有用的。怎么样将图片流显示在页面中呢?解决方法:(一)、response-type为blob类型a. 把response-type改为blob类型b.在请求后端接口返回data时,调用window的URL方法。//完整代码<img :src="imgUrl " />axi
·
遇到的问题:
在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;
})
更多推荐
已为社区贡献2条内容
所有评论(0)