聊聊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