js 二進制流轉(zhuǎn)圖片的操作方法
前端接收后端返回的二進制流并轉(zhuǎn)換成圖片驗證碼

一、接收數(shù)據(jù)
1)如果后端的接口是get方法,可以直接使用img標簽
<img id="canvas_img" src="http://localhost:9999/api/image_verifty" alt="">
2)使用axios
html
<img id="canvas_img" src="" alt="">
js
axios({
url:'/api/image_verifty',
method:'get', //默認get方法,可以不寫
responseType:'arraybuffer' //或者是blob
}).then(res=>{
let canvas_img = document.querySelector('#canvas_img');
let imageType = res.headers['content-type']; //獲取圖片類型
const blob = new Blob([res.data], { type: imageType })
const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
canvas_img.src = imageUrl;
canvas_img.onload = function(e) {
window.URL.revokeObjectURL(canvas_img.src); //釋放URL.createObjectURL()創(chuàng)建的對象
};
})3)使用ajax
html
<img id="canvas_img" src="" alt="">
js
let xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
// 兼容 IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/api/image_verifty",true);
xmlhttp.responseType = 'arraybuffer'; //或者是blob
xmlhttp.onload = function(){
//請求成功
if (this.status == 200) {
let canvas_img = document.querySelector('#canvas_img');
let imageType = xmlhttp.getResponseHeader("Content-Type");
const blob = new Blob([this.response], { type: imageType });
const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob);
canvas_img.src = imageUrl;
canvas_img.onload = function(e) {
window.URL.revokeObjectURL(canvas_img.src); //釋放URL.createObjectURL()創(chuàng)建的對象
};
}
}
xmlhttp.send();二、報錯處理
當返回JSON格式的報錯信息時,responseType已經(jīng)將返回的數(shù)據(jù)轉(zhuǎn)成了二進制,我們需要將二進制轉(zhuǎn)化成JSON數(shù)據(jù)才能獲取錯誤提示。

1)responseType為blob
axios({
url:'/api/image_verifty',
responseType:'blob'
}).then(res=>{
const reader = new FileReader(); //創(chuàng)建一個FileReader實例
reader.readAsText(res.data, 'utf-8'); //讀取文件,結(jié)果用字符串形式表示
reader.onload=()=>{//讀取完成后,**獲取reader.result**
try{
const msg = JSON.parse(reader.result); //這一步報錯則返回的是二進制流圖片,不報錯則返回的是JSON的錯誤提示數(shù)據(jù)
console.log(msg) //msg為轉(zhuǎn)換后的JSON數(shù)據(jù)
}catch{
let imageType = res.headers['content-type'];
let canvas_img = document.querySelector('#canvas_img');
const blob = new Blob([res.data], { type: imageType })
const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
canvas_img.src = imageUrl;
canvas_img.onload = function(e) {
window.URL.revokeObjectURL(canvas_img.src);
};
}
}
})2)responseType為arraybuffer
axios({
url:'/api/image_verifty',
responseType:'arraybuffer'
}).then(res=>{
try{
const utf8decoder = new TextDecoder()
const u8arr = new Uint8Array(res.data)
const temp = utf8decoder.decode(u8arr) // 將二進制數(shù)據(jù)轉(zhuǎn)為字符串
const msg = JSON.parse(temp) //這一步報錯則返回的是二進制流圖片,不報錯則返回的是JSON的錯誤提示數(shù)據(jù)
console.log(msg) //msg為轉(zhuǎn)換后的JSON數(shù)據(jù)
}catch{
let imageType = res.headers['content-type'];
let canvas_img = document.querySelector('#canvas_img');
const blob = new Blob([res.data], { type: imageType })
const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
canvas_img.src = imageUrl;
canvas_img.onload = function(e) {
window.URL.revokeObjectURL(canvas_img.src);
};
}
})三、補充(文件下載)
以上的方法也適用于下載各類文件
接口的響應頭信息如下:

axios({
url:'/export',
method:'get',
responseType:'blob'
}).then(res=>{
const { data, headers } = res;
/*獲取文件名,這里的正則表達式要根據(jù)響應頭"content-disposition"信息來變化,含義是將headers['content-disposition']的內(nèi)容替換成第一個括號里的內(nèi)容(即文件名)并返回。
如果響應頭:
content-disposition:attachment; filename="測試文件名.xls"
注意分號與filename間多了空格,filename后還有個雙引號
所以:
const fileName = headers['content-disposition'].replace(/\w+; filename="(.*)"/, '$1')
*/
const fileName = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1')
//獲取文件流及文件類型
const blob = new Blob([data], { type: headers['content-type'] })
let a = document.createElement('a')
let url = window.URL.createObjectURL(blob)
a.href = url
a.download = decodeURI(fileName)
a.style.display = 'none'
document.body.appendChild(a)
a.click()
a.parentNode.removeChild(a)
window.URL.revokeObjectURL(url)
})參考:JavaScript如何轉(zhuǎn)換二進制數(shù)據(jù)顯示成圖片,見文末補充介紹。
參考:如何將blob返回值轉(zhuǎn)換為json格式
參考:js 二進制流文件下載(接口返回二進制流)亂碼處理
參考:前端使用axios實現(xiàn)下載文件功能的詳細過程
補充:
JavaScript如何轉(zhuǎn)換二進制數(shù)據(jù)顯示成圖片
使用JavaScript調(diào)用API返回了二進制數(shù)據(jù)格式的圖片,該如何顯示到網(wǎng)頁上?
首先,直接使用XMLHttpRequest,而不是AJAX,原因已經(jīng)在前一篇文章中解釋。并將responseType設(shè)置為arraybuffer
var xhr = new XMLHttpRequest();
xhr.open('GET', '/my/image/name.png', true);
xhr.responseType = 'arraybuffer';然后,將二進制轉(zhuǎn)成圖片源,我從網(wǎng)上搜索找到以下兩種方法,大家可以隨意選擇自己喜歡的。
方法一
var uInt8Array = new Uint8Array(xhr.response);
var i = uInt8Array.length;
var binaryString = new Array(i);
while (i--) {
binaryString[i] = String.fromCharCode(uInt8Array[i]);
}
var data = binaryString.join('');
var imageType = xhr.getResponseHeader("Content-Type");
$('#image').attr("src", "data:" + imageType + ";base64," + data)方法二
var imageType = xhr.getResponseHeader("Content-Type");
var blob = new Blob([xhr.response], { type: imageType });
var imageUrl = (window.URL || window.webkitURL).createObjectURL(blob);
$('#image').attr("src", imageUrl);到此這篇關(guān)于js 二進制流轉(zhuǎn)圖片的文章就介紹到這了,更多相關(guān)js 二進制流轉(zhuǎn)圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
js 數(shù)組 find,some,filter,reduce區(qū)別詳解
區(qū)分清楚Array中filter、find、some、reduce這幾個方法的區(qū)別,根據(jù)它們的使用場景更好的應用在日常編碼中。具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-06-06
產(chǎn)制造追溯系統(tǒng)之通過微信小程序?qū)崿F(xiàn)移動端報表平臺
這篇文章主要介紹了產(chǎn)制造追溯系統(tǒng)-通過微信小程序?qū)崿F(xiàn)移動端報表平臺 ,本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06
前端常見的數(shù)據(jù)緩存方案及其實現(xiàn)細節(jié)
緩存機制隨處可見,優(yōu)秀的緩存機制可以縮短網(wǎng)頁請求資源的事件,減少延遲,這篇文章主要介紹了前端常見的數(shù)據(jù)緩存方案及其實現(xiàn)的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2025-07-07
JavaScript數(shù)據(jù)存儲 Cookie篇
這篇文章主要為大家介紹了JavaScript數(shù)據(jù)存儲 Cookie篇,感興趣的朋友可以參考一下2016-07-07

