1. 程式人生 > 實用技巧 >前端中的二進位制以及相關操作與轉換

前端中的二進位制以及相關操作與轉換

感覺這篇文章關於前端二進位制處理寫的很好,參考一下。引用:前端中的二進位制以及相關操作與轉換

本篇文章總結了瀏覽器端的二進位制以及有關資料之間的轉化,如 ArrayBuffer,TypedArray,Blob,DataURL,ObjectURL,Text 之間的互相轉換。為了更好的理解與方便以後的查詢,特意做了一張圖做總結。

二進位制相關資料型別

在此之前,首先簡單介紹下幾種相關的資料型別,更多文件請參考 MDN

ArrayBuffer && TypedArray

TypedArray 是 ES6+ 新增的描述二進位制資料的類陣列資料結構。但它本身不可以被例項化,甚至無法訪問,你可以把它理解為 Abstract Class 或者 Interface。而基於 TypedArray,有如下資料型別。

  • Uint8Array

Uint 代表陣列的每一項是無符號整型
8 代表資料的每一項佔 8 個位元位,即一個位元組

  • Int8Array
  • Uint8Array
  • Int16Array
  • ...
const array = new Int8Array([1, 2, 3])

// .length 代表資料大小
// 3
array.length

// .btyeLength 代表資料所佔位元組大小
array.byteLength

ArrayBuffer 代表二進位制資料結構,只讀。需要轉化為 TypedArray 進行操作。

const array = new Int16Array([1, 2, 3])

// TypedArray -> ArrayBuffer
array.buffer

// ArrayBuffer -> TypedArray
new Int16Array(array.buffer)

// buffer.length 代表資料所佔用位元組大小
array.buffer.length === array.byteLength

連線多個 TypedArray

TypedArray 沒有像陣列那樣的 Array.prototype.concat 方法用來連線多個 TypedArray。不過它提供了 TypedArray.prototype.set 可以用來間接連線字串。原理就是先分配一塊空間足以容納需要連線的 TypedArray,然後逐一在對應位置疊加、

// 在位移 offset 位置放置 typedarray
typedarray.set(typedarray, offset)

function concatenate(constructor, ...arrays) {
  let length = 0;
  for (let arr of arrays) {
    length += arr.length;
  }
  let result = new constructor(length);
  let offset = 0;
  for (let arr of arrays) {
    result.set(arr, offset);
    offset += arr.length;
  }
  return result;
}

concatenate(Uint8Array, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]))

Blob

Blob 是瀏覽器端的類檔案物件。操作 Blob 需要使用資料型別 FileReader。
FileReader 有以下方法,可以把 Blob 轉化為其它資料

  • FileReader.prototype.readAsArrayBuffer
  • FileReader.prototype.readAsText
  • FileReader.prototype.readAsDataURL
  • FileReader.prototype.readAsBinaryString
const blob = new Blob('hello'.split(''))

// 表示檔案的大小
blob.size

const array = new Uint8Array([128, 128, 128])
const blob2 = new Blob([array])

function readBlob (blob, type) {
  return new Promise(resolve => {
    const reader = new FileReader()
    reader.onload = function (e) {
      resolve(e.target.result)  
    }
    reader.readAsArrayBuffer(blob)
  })
}

readBlob(blob, 'DataURL').then(url => console.log(url))

資料輸入

資料輸入或者叫資源的請求可以分為以下兩種途徑

  • 通過 url 地址請求網路資源
  • 通過檔案上傳請求本地資源

fetch

fetch 應該是大家比較熟悉的,但大多使用環境比較單一,一般用來請求 json 資料。其實, 它也可以設定返回資料格式為 Blob 或者 ArrayBuffer。

fetch 返回一個包含 Response 物件的 Promise,Response 有以下方法

  • Response.prototype.arrayBuffer
  • Response.prototype.blob
  • Response.prototype.text
  • Response.prototype.json
fetch('/api/ping').then(res => {
  // true
  console.log(res instanceof Response)
  // 最常見的使用
  return res.json()

  // 返回 Blob
  // return res.blob()

  // 返回 ArrayBuffer
  // return res.arrayBuffer()
})

另外,Response API 既可以可以使用 TypedArray,Blob,Text 作為輸入,又可以使用它們作為輸出。這意味著關於這三種資料型別的轉換完全可以通過 Response

xhr

xhr 可以設定 responseType 接收合適的資料型別

const request = new XMLHttpRequest()
request.responseType = 'arraybuffer'
request.responseType = 'blob'

File

本地檔案可以通過 input[type=file] 來上傳檔案。

<input type="file" id="input">

當上傳成功後,可以通過 document.getElementById('input').files[0] 獲取到上傳的檔案,即一個 File 物件,它是 Blob 的子類,可以通過 FileReader 或者 Response 獲取檔案內容。

資料輸出

或者叫資料展示或者下載,資料經二進位制處理後可以由 url 表示,然後通過 image, video 等元素引用或者直接下載。

Data URL

Data URL 即 Data As URL。所以, 如果資源過大,地址便會很長。 使用以下形式表示。

data:[<mediatype>][;base64],<data>

//先來一個 hello, world。把以下地址粘入位址列,會訪問到 hello, world
data:text/html,<h1>Hello%2C%20World!</h1>

Base64 編碼與解碼

Base64 使用大小寫字母,數字,+ 和 / 64 個字元來編碼資料,所以稱為 Base64。經編碼後,文字體積會變大 1/3
在瀏覽器中,可以使用 atob 和 btoa 編碼解碼資料。

// aGVsbG8=
btoa('hello')

Object URL

可以使用瀏覽器新的API URL 物件生成一個地址來表示 Blob 資料。

// 貼上生成的地址,可以訪問到 hello, world
// blob:http://host/27254c37-db7a-4f2f-8861-0cf9aec89a64
URL.createObjectURL(new Blob('hello, world'.split('')))

下載

資源的下載可以利用 FileSaver 。

import { saveAs } from 'file-saver';
saveAs(Blob/File/Url, optional DOMString filename, optional Object { autoBom })

適配性更好,推薦!

也簡單寫一個函式,用來下載一個連結

function download (url, name) {
  const a = document.createElement('a')
  a.download = name
  a.rel = 'noopener'
  a.href = url
  // 觸發模擬點選
  a.dispatchEvent(new MouseEvent('click'))
  // 或者 a.click(
}

二進位制資料轉換


以上是二進位制資料間的轉換圖,有一些轉換可以直接通過 API,有些則需要程式碼,以下貼幾種常見轉換的程式碼

String to TypedArray

由字串到 TypedArray 的轉換,可以通過 String -> Blob -> ArrayBuffer -> TypedArray 的途徑。

const name = '山月'
const blob = new Blob(name.split(''))

readBlob(blob, 'ArrayBuffer').then(buffer => new Uint8Array(buffer))

也可以通過 Response API 直接轉換 String -> ArrayBuffer -> TypedArray

const name = '山月'

new Response(name).arrayBuffer(buffer => new Uint8Array(buffer))

這上邊兩種方法都是直接通過 API 來轉化.

使用 enodeURIComponent 把字串轉化為 utf8,再進行構造 TypedArray。

function stringToTypedArray(s) {
  const str = encodeURIComponent(s)
  const binstr = str.replace(/%([0-9A-F]{2})/g, (_, p1) => {
    return String.fromCharCode('0x' + p1)
  })
  return new Uint8Array(binstr.split('').map(x => x.charCodeAt(0)))
}

拼接音訊

參考:JavaScript 拼接audio

json 資料轉化為 demo.json 並下載檔案

json 視為字串,由以上整理的轉換圖得出途徑

Text -> DataURL

除了使用 DataURL,還可以轉化為 Object URL 進行下載。

Text -> Blob -> Object URL

const json = {
  a: 3,
  b: 4,
  c: 5
}
const str = JSON.stringify(json, null, 2)

const dataUrl = `data:,${str}`
const url = URL.createObjectURL(new Blob(str.split('')))

download(dataUrl, 'demo.json')
download(url, 'demo1.json')

URL獲取blob

私心記錄一下,使用xhr或axios

function getBlob(url: string): Promise<Blob> {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      }
    };
    xhr.send();
  });
}

//或者使用axios
async function getBlob(url: string): Promise<Blob> {
  return new Promise(resolve => {
    axios.get(url, { responseType: "blob" }).then(resp => resolve(resp.data));
  });
}