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


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

本篇文章總結了瀏覽器端的二進制以及有關數據之間的轉化,如 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 })

Pass { autoBom: true } if you want FileSaver.js to automatically provide Unicode text encoding hints (see: byte order mark). Note that this is only done if your blob type has charset=utf-8 set.

適配性更好,推薦!

也簡單寫一個函數,用來下載一個鏈接

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
export async function getBlob(url: string): Promise<Blob> {
  const blob = await axios.get(url, { responseType: "blob" });
  return blob.data;
}


免責聲明!

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



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