后台返回流图片的处理方式。(原生,JQ,VUE)

原生
var url = "....."; var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = "blob"; xhr.setRequestHeader("client_type", "DESKTOP_WEB"); xhr.onload = function() { if (this.status == 200) { var blob = this.response; var img = document.createElement("img"); img.onload = function(e) { window.URL.revokeObjectURL(img.src); }; img.src = window.URL.createObjectURL(blob); $("#imgcontainer").html(img); } } xhr.send();

JQ
jquery做了这么久了 一个ajax方法还停留在几年前的xmlhttprequest 1的版本中,不支持流文件!!!

datatype数据类型

发现竟然没有二进制数据选项,那是不是返回的数据被默认以文本形式返回了。



vue

(一)、response-type为blob类型

a. 把response-type改为blob类型

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

axios.get('url',{

params:{

key:this.key

responseType: 'blob',

}).then(response => {

this.imgUrl = window.URL.createObjectURL(res.data);

})

 

(二)、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;

})



posted @ 2021-01-06 18:43  勒布朗_詹姆斯  阅读(1245)  评论(0编辑  收藏  举报