Uint8Array.prototype.toBase64()
Uint8Array 例項的 toBase64() 方法會根據此 Uint8Array 物件中的資料返回一個 base64 編碼的字串。
此方法應優於 Window.btoa(),特別是當您已經有一個包含物件的 Uint8Array 時,因為您無需先將其轉換為字串。
語法
js
toBase64()
toBase64(options)
引數
options可選-
一個自定義 base64 字串格式的物件。它可以包含以下屬性:
alphabet可選-
一個指定要使用的 base64 字母表的字串。它可以是以下之一:
"base64"(預設)-
使用標準的 base64 字母表對輸入進行編碼,該字母表使用
+和/。 "base64url"-
使用 URL 安全的 base64 字母表對輸入進行編碼,該字母表使用
-和_。
omitPadding可選-
一個指定是否在 base64 字串末尾省略填充字元 (
=) 的布林值。預設為false。
返回值
一個表示 Uint8Array 中資料的 base64 編碼字串。
異常
TypeError-
在以下情況之一中丟擲
options物件不是物件或undefined。options.alphabet的值不是預期的值,或者為undefined。
示例
編碼二進位制資料
此示例使用預設的 alphabet 和 omitPadding 選項將 Uint8Array 中的資料編碼為 base64 字串。
js
const uint8Array = new Uint8Array([29, 233, 101, 161]);
console.log(uint8Array.toBase64()); // "HelloQ=="
編碼無填充資料
js
const uint8Array = new Uint8Array([29, 233, 101, 161]);
console.log(uint8Array.toBase64({ omitPadding: true })); // "HelloQ"
使用 URL 安全字母表編碼資料
此示例使用 URL 安全字母表將 base64 編碼字串填充到 URLSearchParams 物件中。
js
const uint8Array = new Uint8Array([46, 139, 222, 255, 42, 46]);
const base64 = uint8Array.toBase64({ alphabet: "base64url" });
const params = new URLSearchParams();
params.set("data", base64);
console.log(params.toString()); // "data=Love_you"
流式編碼
此示例改編自 原始提案,展示瞭如何在使用者空間實現流式傳輸。它透過 stream 選項模擬了 TextEncoder API。
js
class Base64Encoder {
#extra;
#extraLength;
constructor() {
this.#extra = new Uint8Array(3);
this.#extraLength = 0;
}
// Partly derived from https://github.com/lucacasonato/base64_streams/blob/main/src/iterator/encoder.ts
encode(chunk = Uint8Array.of(), options = {}) {
const stream = options.stream ?? false;
if (this.#extraLength > 0) {
const bytesNeeded = 3 - this.#extraLength;
const bytesAvailable = Math.min(bytesNeeded, chunk.length);
this.#extra.set(chunk.subarray(0, bytesAvailable), this.#extraLength);
chunk = chunk.subarray(bytesAvailable);
this.#extraLength += bytesAvailable;
}
if (!stream) {
// assert: this.#extraLength.length === 0 || this.#extraLength === 3 || chunk.length === 0
const prefix = this.#extra.subarray(0, this.#extraLength).toBase64();
this.#extraLength = 0;
return prefix + chunk.toBase64();
}
let extraReturn = "";
if (this.#extraLength === 3) {
extraReturn = this.#extra.toBase64();
this.#extraLength = 0;
}
const remainder = chunk.length % 3;
if (remainder > 0) {
this.#extra.set(chunk.subarray(chunk.length - remainder));
this.#extraLength = remainder;
chunk = chunk.subarray(0, chunk.length - remainder);
}
return extraReturn + chunk.toBase64();
}
}
const encoder = new Base64Encoder();
console.log(
encoder.encode(Uint8Array.of(72, 101, 108, 108, 111), { stream: true }),
);
// "SGVs"
console.log(
encoder.encode(Uint8Array.of(32, 87, 111, 114, 108, 100), { stream: true }),
);
// "bG8gV29y"
console.log(encoder.encode());
// "bGQ="
規範
| 規範 |
|---|
| Uint8Array 與 base64 的相互轉換 # sec-uint8array.prototype.tobase64 |
瀏覽器相容性
載入中…