淺談JS的二進(jìn)制家族
Blob: 前端的一個(gè)專門用于支持文件操作的二進(jìn)制對(duì)象
ArrayBuffer:前端的一個(gè)通用的二進(jìn)制緩沖區(qū),類似數(shù)組,但在API和特性上卻有諸多不同
Buffer:Node.js提供的一個(gè)二進(jìn)制緩沖區(qū),常用來處理I/O操作
Blob我們首先來介紹Blob,Blob是用來支持文件操作的。簡(jiǎn)單的說:在JS中,有兩個(gè)構(gòu)造函數(shù) File 和 Blob, 而File繼承了所有Blob的屬性。
所以在我們看來,F(xiàn)ile對(duì)象可以看作一種特殊的Blob對(duì)象。
在前端工程中,我們?cè)谀男┎僮髦锌梢垣@得File對(duì)象呢? 請(qǐng)看:
(備注:目前 File API規(guī)范的狀態(tài)為Working Draft)
我們上面說了,F(xiàn)ile對(duì)象是一種特殊的Blob對(duì)象,那么它自然就可以直接調(diào)用Blob對(duì)象的方法。讓我們看一看Blob具體有哪些方法,以及能夠用它們實(shí)現(xiàn)哪些功能
通過window.URL.createObjectURL方法可以把一個(gè)blob轉(zhuǎn)化為一個(gè)Blob URL,并且用做文件下載或者圖片顯示的鏈接。
Blob URL所實(shí)現(xiàn)的下載或者顯示等功能,僅僅可以在單個(gè)瀏覽器內(nèi)部進(jìn)行。而不能在服務(wù)器上進(jìn)行存儲(chǔ),亦或者說它沒有在服務(wù)器端存儲(chǔ)的意義。
下面是一個(gè)Blob的例子,可以看到它很短
blob:d3958f5c-0777-0845-9dcf-2cb28783acaf
和冗長(zhǎng)的Base64格式的Data URL相比,Blob URL的長(zhǎng)度顯然不能夠存儲(chǔ)足夠的信息,這也就意味著它只是類似于一個(gè)瀏覽器內(nèi)部的“引用“。從這個(gè)角度看,Blob URL是一個(gè)瀏覽器自行制定的一個(gè)偽協(xié)議
Blob下載文件我們可以通過window.URL.createObjectURL,接收一個(gè)Blob(File)對(duì)象,將其轉(zhuǎn)化為Blob URL,然后賦給 a.download屬性,然后在頁面上點(diǎn)擊這個(gè)鏈接就可以實(shí)現(xiàn)下載了
<!-- html部分 --><a id='h'>點(diǎn)此進(jìn)行下載</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, 對(duì)IE可通過window.navigator.msSaveBlob方法或其他進(jìn)行優(yōu)化(IE10/11)
運(yùn)行結(jié)果
window.URL.createObjectURL生成的Blob URL還可以賦給img.src,從而實(shí)現(xiàn)圖片的顯示
<!-- html部分 --><input type='file' id=’f’ /><img id=’img’ /><!-- 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 () {// 釋放一個(gè)之前通過調(diào)用 URL.createObjectURL創(chuàng)建的 URL 對(duì)象window.URL.revokeObjectURL(url); } }, false);</script>
運(yùn)行結(jié)果
前端
<!-- 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(’---------------’); }});
文件內(nèi)容
According to the Zhanjiang commerce bureau, the actual amount of foreign capital utilized in Zhanjiang from January to October this year was
運(yùn)行結(jié)果
如果想要讀取Blob或者文件對(duì)象并轉(zhuǎn)化為其他格式的數(shù)據(jù),可以借助FileReader對(duì)象的API進(jìn)行操作
FileReader.readAsText(Blob):將Blob轉(zhuǎn)化為文本字符串 FileReader.readAsArrayBuffer(Blob): 將Blob轉(zhuǎn)為ArrayBuffer格式數(shù)據(jù) FileReader.readAsDataURL(): 將Blob轉(zhuǎn)化為Base64格式的Data URL下面我們嘗試把一個(gè)文件的內(nèi)容通過字符串的方式讀取出來
<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);
運(yùn)行結(jié)果
上面介紹了Blob的用法,我們不難發(fā)現(xiàn),Blob是針對(duì)文件的,或者可以說它就是一個(gè)文件對(duì)象,同時(shí)呢我們發(fā)現(xiàn)Blob欠缺對(duì)二進(jìn)制數(shù)據(jù)的細(xì)節(jié)操作能力,比如如果如果要具體修改某一部分的二進(jìn)制數(shù)據(jù),Blob顯然就不夠用了,而這種細(xì)粒度的功能則可以由下面介紹的ArrayBuffer來完成。
ArrayBuffer讓我們用一張圖看下ArrayBuffer的大體的功能
同時(shí)要說明,ArrayBuffer跟JS的原生數(shù)組有很大的區(qū)別,如圖所示
下面一一進(jìn)行細(xì)節(jié)的介紹
通過ArrayBuffer的格式讀取本地?cái)?shù)據(jù)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);
運(yùn)行結(jié)果
通過xhr.responseType = 'arraybuffer' 指定響應(yīng)的數(shù)據(jù)類型
在onload回調(diào)里打印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)
運(yùn)行結(jié)果
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對(duì)ArrayBuffer進(jìn)行寫操作
const buffer = new ArrayBuffer(16);const view = new DataView(buffer);view.setInt8(2, 42);console.log(view.getInt8(2));// 輸出: 42Buffer
Buffer是Node.js提供的對(duì)象,前端沒有。 它一般應(yīng)用于IO操作,例如接收前端請(qǐng)求數(shù)據(jù)時(shí)候,可以通過以下的Buffer的API對(duì)接收到的前端數(shù)據(jù)進(jìn)行整合
例子如下:
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');
運(yùn)行結(jié)果
Node端輸出
asdasdsadfsdfsadasdas
以上就是淺談JS的二進(jìn)制家族的詳細(xì)內(nèi)容,更多關(guān)于JS的二進(jìn)制家族的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
