后台返回流圖片的處理方式。(原生,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;

})




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM