strToBase64
将字符串转换为 Base64 编码,支持中文字符。
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
deps.btoa | Base64Encoder['btoa'] | Base64 编码函数 |
环境要求
- 浏览器环境: 使用
window.btoa - Node.js 环境: 使用
Buffer.from(str, 'binary').toString('base64')
typescript
// 浏览器环境
const deps = { btoa: window.btoa.bind(window) }
// Node.js 环境
const deps = {
btoa: (str: string) => Buffer.from(str, 'binary').toString('base64')
}函数签名
typescript
function strToBase64(
str: string,
deps: Base64Deps
): string
interface Base64Deps {
btoa: Base64Encoder['btoa']
}参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
str | string | 是 | 要编码的字符串 |
deps | Base64Deps | 是 | 依赖注入对象,包含 btoa 编码函数 |
返回值
| 类型 | 说明 |
|---|---|
string | Base64 编码后的字符串 |
工作原理
- 使用
encodeURIComponent对输入字符串进行 URI 编码(处理中文等特殊字符) - 将 URI 编码后的字符串转换为二进制格式
- 调用
btoa函数进行 Base64 编码 - 返回编码后的字符串
通过先进行 URI 编码,可以正确处理中文、表情符号等多字节字符,避免 Base64 编码时出现乱码。