聊聊JS的二進制家族:Blob、ArrayBuffer和Buffer


事實上,前端很少涉及對二進制數據的處理,但即便如此,我們偶爾總能在角落里看見它們的身影。

今天我們就來聊一聊前端的二進制家族:Blob、ArrayBuffer和Buffer

 

概述

  • Blob: 前端的一個專門用於支持文件操作的二進制對象

  • ArrayBuffer:前端的一個通用的二進制緩沖區,類似數組,但在API和特性上卻有諸多不同

  • Buffer:Node.js提供的一個二進制緩沖區,常用來處理I/O操作 

Blob

我們首先來介紹Blob,Blob是用來支持文件操作的。簡單的說:在JS中,有兩個構造函數 File 和 Blob, 而File繼承了所有Blob的屬性。

所以在我們看來,File對象可以看作一種特殊的Blob對象。

 

在前端工程中,我們在哪些操作中可以獲得File對象呢? 請看:

(備注:目前 File API規范的狀態為Working Draft)

 

我們上面說了,File對象是一種特殊的Blob對象,那么它自然就可以直接調用Blob對象的方法。讓我們看一看Blob具體有哪些方法,以及能夠用它們實現哪些功能

 

 

 

Blob實戰

通過window.URL.createObjectURL方法可以把一個blob轉化為一個Blob URL,並且用做文件下載或者圖片顯示的鏈接。

Blob URL所實現的下載或者顯示等功能,僅僅可以在單個瀏覽器內部進行。而不能在服務器上進行存儲,亦或者說它沒有在服務器端存儲的意義。

下面是一個Blob的例子,可以看到它很短

blob:d3958f5c-0777-0845-9dcf-2cb28783acaf

和冗長的Base64格式的Data URL相比,Blob URL的長度顯然不能夠存儲足夠的信息,這也就意味着它只是類似於一個瀏覽器內部的“引用“。從這個角度看,Blob URL是一個瀏覽器自行制定的一個偽協議 

Blob下載文件

我們可以通過window.URL.createObjectURL,接收一個Blob(File)對象,將其轉化為Blob URL,然后賦給 a.download屬性,然后在頁面上點擊這個鏈接就可以實現下載了

<!-- html部分 -->
<a id="h">點此進行下載</a>
<!-- js部分 -->
<script>
  var blob = new Blob(["Hello World"]);
  var url = window.URL.createObjectURL(blob);
  var a = document.getElementById("h");
  a.download = "helloworld.txt";
  a.href = url;
</script>

 

備注:download屬性不兼容IE, 對IE可通過window.navigator.msSaveBlob方法或其他進行優化(IE10/11)

 

運行結果

 

Blob圖片本地顯示

window.URL.createObjectURL生成的Blob URL還可以賦給img.src,從而實現圖片的顯示

 

<!-- html部分 -->
<input type="file" id='f' />
<img id='img' style="width: 200px;height:200px;" />
<!-- js部分 -->
<script>
  document.getElementById('f').addEventListener('change', function (e) {
    var file = this.files[0];
    const img = document.getElementById('img');
    const url = window.URL.createObjectURL(file);
    img.src = url;
    img.onload = function () {
        // 釋放一個之前通過調用 URL.createObjectURL創建的 URL 對象
        window.URL.revokeObjectURL(url);
    }
  }, false);
</script>
 

 

運行結果

 

Blob文件分片上傳

  • 通過Blob.slice(start,end)可以分割大Blob為多個小Blob

  • xhr.send是可以直接發送Blob對象的

前端

 

<!-- html部分 -->
<input type="file" id='f' />
<!-- js部分 -->
<script>
  function upload(blob) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/ajax', true);
    xhr.setRequestHeader('Content-Type', 'text/plain')
    xhr.send(blob);
  }
  document.getElementById('f').addEventListener('change', function (e) {
    var blob = this.files[0];
    const CHUNK_SIZE = 20; .
    const SIZE = blob.size;
    var start = 0;
    var end = CHUNK_SIZE;
    while (start < SIZE) {
        upload(blob.slice(start, end));
        start = end;
        end = start + CHUNK_SIZE;
    }
  }, false);
</script>
 

 

Node端

app.use(async (ctx, next) => {
    await next();
    if (ctx.path === '/ajax') {
        const req = ctx.req;
        const body = await parse(req);
        ctx.status = 200;
        console.log(body);
        console.log('---------------');
    }
});

 

文件內容

According to the Zhanjiang commerce bureau, the actual amount of foreign capital utilized in Zhanjiang from January to October this year was

 

 

運行結果

 

本地讀取文件內容

如果想要讀取Blob或者文件對象並轉化為其他格式的數據,可以借助FileReader對象的API進行操作

  • FileReader.readAsText(Blob):將Blob轉化為文本字符串

  • FileReader.readAsArrayBuffer(Blob): 將Blob轉為ArrayBuffer格式數據

  • FileReader.readAsDataURL(): 將Blob轉化為Base64格式的Data URL

 

下面我們嘗試把一個文件的內容通過字符串的方式讀取出來

<input type="file" id='f' />

document.getElementById('f').addEventListener('change', function (e) { var file = this.files[0]; const reader = new FileReader(); reader.onload = function () { const content = reader.result; console.log(content); } reader.readAsText(file); }, false);
 

運行結果

 

 

上面介紹了Blob的用法,我們不難發現,Blob是針對文件的,或者可以說它就是一個文件對象,同時呢我們發現Blob欠缺對二進制數據的細節操作能力,比如如果如果要具體修改某一部分的二進制數據,Blob顯然就不夠用了,而這種細粒度的功能則可以由下面介紹的ArrayBuffer來完成。

 

ArrayBuffer

讓我們用一張圖看下ArrayBuffer的大體的功能

同時要說明,ArrayBuffer跟JS的原生數組有很大的區別,如圖所示

 

下面一一進行細節的介紹

 

通過ArrayBuffer的格式讀取本地數據

document.getElementById('f').addEventListener('change', function (e) {
  const file = this.files[0];
  const fileReader = new FileReader();
  fileReader.onload = function () {
    const result = fileReader.result;
    console.log(result)
  }
  fileReader.readAsArrayBuffer(file);
}, false);

 

 

運行結果

通過ArrayBuffer的格式讀取Ajax請求數據

  • 通過xhr.responseType = "arraybuffer" 指定響應的數據類型

  • 在onload回調里打印xhr.response

前端

const xhr = new XMLHttpRequest();
xhr.open("GET", "ajax", true);
xhr.responseType = "arraybuffer";
xhr.onload = function () {
    console.log(xhr.response)
}
xhr.send();

 

 

Node端

const app = new Koa();
app.use(async (ctx) => {
  if (pathname = '/ajax') {
        ctx.body = 'hello world';
        ctx.status = 200;
   }
}).listen(3000)

 

運行結果

通過TypeArray對ArrayBuffer進行寫操作

const typedArray1 = new Int8Array(8);
typedArray1[0] = 32;

const typedArray2 = new Int8Array(typedArray1);
typedArray2[1] = 42;
 
console.log(typedArray1);
//  output: Int8Array [32, 0, 0, 0, 0, 0, 0, 0]
 
console.log(typedArray2);
//  output: Int8Array [32, 42, 0, 0, 0, 0, 0, 0]

 

 

通過DataView對ArrayBuffer進行寫操作

const buffer = new ArrayBuffer(16);
const view = new DataView(buffer);
view.setInt8(2, 42);
console.log(view.getInt8(2));
// 輸出: 42

 

Buffer

Buffer是Node.js提供的對象,前端沒有。 它一般應用於IO操作,例如接收前端請求數據時候,可以通過以下的Buffer的API對接收到的前端數據進行整合

Buffer實戰

例子如下:

Node端(Koa)

const app = new Koa();
app.use(async (ctx, next) => {
    if (ctx.path === '/ajax') {
        const chunks = [];
        const req = ctx.req;
        req.on('data', buf => {
            chunks.push(buf);
        })
        req.on('end', () => {
            let buffer = Buffer.concat(chunks);
            console.log(buffer.toString())
        })
    }
});
app.listen(3000)

 

前端

const xhr = new XMLHttpRequest();
xhr.open("POST", "ajax", true);
xhr.setRequestHeader('Content-Type', 'text/plain')
xhr.send("asdasdsadfsdfsadasdas");

 

運行結果

Node端輸出

asdasdsadfsdfsadasdas

 


免責聲明!

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



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