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

一、接收數(shù)據(jù)
1)如果后端的接口是get方法,可以直接使用img標(biāo)簽
<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();二、報錯處理
當(dāng)返回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);
};
}
})三、補充(文件下載)
以上的方法也適用于下載各類文件
接口的響應(yīng)頭信息如下:

axios({
url:'/export',
method:'get',
responseType:'blob'
}).then(res=>{
const { data, headers } = res;
/*獲取文件名,這里的正則表達式要根據(jù)響應(yīng)頭"content-disposition"信息來變化,含義是將headers['content-disposition']的內(nèi)容替換成第一個括號里的內(nèi)容(即文件名)并返回。
如果響應(yīng)頭:
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)文章
Bootstrap選項卡與Masonry插件的完美結(jié)合
這篇文章主要介紹了Bootstrap選項卡與Masonry插件的完美結(jié)合的相關(guān)資料,需要的朋友可以參考下2016-07-07
javascript的tab切換原理與效果實現(xiàn)方法
這篇文章主要介紹了javascript的tab切換原理與效果實現(xiàn)方法,實例分析了簡單的tab切換實現(xiàn)技巧,非常具有實用價值,需要的朋友可以參考下2015-01-01
JavaScript 嚴格模式(use strict)用法實例分析
這篇文章主要介紹了JavaScript 嚴格模式(use strict)用法,結(jié)合實例形式分析了JavaScript 嚴格模式的基本功能、用法及操作注意事項,需要的朋友可以參考下2020-03-03
el-date-picker組件隱藏時間組件底部清空按鈕的操作步驟
工作中可能會遇到el-date-picker組件隱藏時間組件底部清空按鈕,接下來通過本文給大家分享el-date-picker組件如何隱藏時間組件底部清空按鈕,需要的朋友可以參考下2024-06-06
第一次接觸神奇的Bootstrap網(wǎng)格系統(tǒng)
第一次接觸神奇的Bootstrap網(wǎng)格系統(tǒng),Bootstrap讓W(xué)eb開發(fā)更迅速、更簡單,感興趣的小伙伴們可以參考一下2016-07-07
weixin-java-miniapp微信小程序登陸具體實現(xiàn)
這篇文章主要介紹了weixin-java-miniapp微信小程序登陸具體實現(xiàn)的相關(guān)資料,包括用戶授權(quán)、獲取code、發(fā)送到后臺、后臺驗證并獲取openid和session_key、返回驗證結(jié)果等步驟,需要的朋友可以參考下2025-02-02
excel操作之Add Data to a Spreadsheet Cell
excel操作之Add Data to a Spreadsheet Cell...2007-06-06
js動態(tài)添加onclick事件可傳參數(shù)與不傳參數(shù)
本節(jié)主要介紹了js動態(tài)添加onclick事件可傳參數(shù)與不傳參數(shù),需要的朋友可以參考下2014-07-07

