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 |
浏览器兼容性
加载中…