欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js 二進(jìn)制流轉(zhuǎn)圖片的操作方法

 更新時間:2023年12月20日 11:22:57   作者:涌。。  
這篇文章主要介紹了js 二進(jìn)制流轉(zhuǎn)圖片的操作方法,接收數(shù)據(jù)大家需要注意,如果后端的接口是get方法,可以直接使用img標(biāo)簽,本文通過示例代碼講解的非常詳細(xì),需要的朋友參考下吧

前端接收后端返回的二進(jìn)制流并轉(zhuǎn)換成圖片驗(yà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',  //默認(rèn)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();

二、報(bào)錯處理

當(dāng)返回JSON格式的報(bào)錯信息時,responseType已經(jīng)將返回的數(shù)據(jù)轉(zhuǎn)成了二進(jìn)制,我們需要將二進(jì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實(shí)例
   reader.readAsText(res.data, 'utf-8'); //讀取文件,結(jié)果用字符串形式表示
   reader.onload=()=>{//讀取完成后,**獲取reader.result**
       try{
           const msg = JSON.parse(reader.result);  //這一步報(bào)錯則返回的是二進(jìn)制流圖片,不報(bào)錯則返回的是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)	// 將二進(jìn)制數(shù)據(jù)轉(zhuǎn)為字符串
       const msg = JSON.parse(temp)		//這一步報(bào)錯則返回的是二進(jìn)制流圖片,不報(bào)錯則返回的是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);
       };
   }
})

三、補(bǔ)充(文件下載)

以上的方法也適用于下載各類文件
接口的響應(yīng)頭信息如下:

axios({
    url:'/export',
    method:'get',
    responseType:'blob'
}).then(res=>{
    const { data, headers } = res;
    /*獲取文件名,這里的正則表達(dá)式要根據(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)換二進(jìn)制數(shù)據(jù)顯示成圖片,見文末補(bǔ)充介紹。
參考:如何將blob返回值轉(zhuǎn)換為json格式
參考:js 二進(jìn)制流文件下載(接口返回二進(jìn)制流)亂碼處理
參考:前端使用axios實(shí)現(xiàn)下載文件功能的詳細(xì)過程

補(bǔ)充:

JavaScript如何轉(zhuǎn)換二進(jìn)制數(shù)據(jù)顯示成圖片

使用JavaScript調(diào)用API返回了二進(jìn)制數(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';

然后,將二進(jìn)制轉(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 二進(jìn)制流轉(zhuǎn)圖片的文章就介紹到這了,更多相關(guān)js 二進(jìn)制流轉(zhuǎn)圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論