亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

淺談JS的二進(jìn)制家族

 更新時(shí)間:2021年05月08日 15:24:56   作者:外婆的  
事實(shí)上,前端很少涉及對(duì)二進(jìn)制數(shù)據(jù)的處理,但即便如此,我們偶爾總能在角落里看見(jiàn)它們的身影。 今天我們就來(lái)聊一聊前端的二進(jìn)制家族:Blob、ArrayBuffer和Buffer

概述

Blob: 前端的一個(gè)專門用于支持文件操作的二進(jìn)制對(duì)象

ArrayBuffer:前端的一個(gè)通用的二進(jìn)制緩沖區(qū),類似數(shù)組,但在API和特性上卻有諸多不同

Buffer:Node.js提供的一個(gè)二進(jìn)制緩沖區(qū),常用來(lái)處理I/O操作

Blob

我們首先來(lái)介紹Blob,Blob是用來(lái)支持文件操作的。簡(jiǎn)單的說(shuō):在JS中,有兩個(gè)構(gòu)造函數(shù) File 和 Blob, 而File繼承了所有Blob的屬性。

所以在我們看來(lái),F(xiàn)ile對(duì)象可以看作一種特殊的Blob對(duì)象。

在前端工程中,我們?cè)谀男┎僮髦锌梢垣@得File對(duì)象呢? 請(qǐng)看:

(備注:目前 File API規(guī)范的狀態(tài)為Working Draft)

我們上面說(shuō)了,F(xiàn)ile對(duì)象是一種特殊的Blob對(duì)象,那么它自然就可以直接調(diào)用Blob對(duì)象的方法。讓我們看一看Blob具體有哪些方法,以及能夠用它們實(shí)現(xiàn)哪些功能

Blob實(shí)戰(zhàn)

通過(guò)window.URL.createObjectURL方法可以把一個(gè)blob轉(zhuǎn)化為一個(gè)Blob URL,并且用做文件下載或者圖片顯示的鏈接。

Blob URL所實(shí)現(xiàn)的下載或者顯示等功能,僅僅可以在單個(gè)瀏覽器內(nèi)部進(jìn)行。而不能在服務(wù)器上進(jìn)行存儲(chǔ),亦或者說(shuō)它沒(méi)有在服務(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下載文件

我們可以通過(guò)window.URL.createObjectURL,接收一個(gè)Blob(File)對(duì)象,將其轉(zhuǎn)化為Blob URL,然后賦給 a.download屬性,然后在頁(yè)面上點(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可通過(guò)window.navigator.msSaveBlob方法或其他進(jìn)行優(yōu)化(IE10/11)

運(yùn)行結(jié)果

Blob圖片本地顯示

window.URL.createObjectURL生成的Blob URL還可以賦給img.src,從而實(shí)現(xiàn)圖片的顯示

<!-- 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 () {
        // 釋放一個(gè)之前通過(guò)調(diào)用 URL.createObjectURL創(chuàng)建的 URL 對(duì)象
        window.URL.revokeObjectURL(url);
    }
  }, false);
</script>

運(yùn)行結(jié)果

Blob文件分片上傳

  • 通過(guò)Blob.slice(start,end)可以分割大Blob為多個(gè)小Blob
  • xhr.send是可以直接發(fā)送Blob對(duì)象的

前端

<!-- 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é)果

本地讀取文件內(nèi)容

如果想要讀取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)容通過(guò)字符串的方式讀取出來(lá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ì)文件的,或者可以說(shuō)它就是一個(gè)文件對(duì)象,同時(shí)呢我們發(fā)現(xiàn)Blob欠缺對(duì)二進(jìn)制數(shù)據(jù)的細(xì)節(jié)操作能力,比如如果如果要具體修改某一部分的二進(jìn)制數(shù)據(jù),Blob顯然就不夠用了,而這種細(xì)粒度的功能則可以由下面介紹的ArrayBuffer來(lái)完成。

ArrayBuffer

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

同時(shí)要說(shuō)明,ArrayBuffer跟JS的原生數(shù)組有很大的區(qū)別,如圖所示

下面一一進(jìn)行細(xì)節(jié)的介紹

通過(guò)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é)果

通過(guò)ArrayBuffer的格式讀取Ajax請(qǐng)求數(shù)據(jù)

通過(guò)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é)果

通過(guò)TypeArray對(duì)ArrayBuffer進(jìn)行寫操作

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]

通過(guò)DataView對(duì)ArrayBuffer進(jìn)行寫操作

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

Buffer

Buffer是Node.js提供的對(duì)象,前端沒(méi)有。 它一般應(yīng)用于IO操作,例如接收前端請(qǐng)求數(shù)據(jù)時(shí)候,可以通過(guò)以下的Buffer的API對(duì)接收到的前端數(shù)據(jù)進(jìn)行整合

Buffer實(shí)戰(zhà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)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論