1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * 字符串(含中文)转 Base64 编码
 * @param {string} str - 要转换的字符串
 * @returns {string} Base64 编码结果
 */
export function stringToBase64(str) {
  // 步骤1:将字符串转为 UTF-8 编码的二进制数据
  const utf8Bytes = new TextEncoder().encode(str);
  // 步骤2:将二进制数据转为 ASCII 字符串(避免 btoa 报错)
  let asciiStr = '';
  for (let i = 0; i < utf8Bytes.length; i++) {
    asciiStr += String.fromCharCode(utf8Bytes[i]);
  }
  // 步骤3:转 Base64
  return btoa(asciiStr);
}
 
/**
 * Base64 编码转回字符串(含中文)
 * @param {string} base64Str - Base64 编码字符串
 * @returns {string} 原字符串
 */
export function base64ToString(base64Str) {
  // 步骤1:Base64 解码为 ASCII 字符串
  const asciiStr = atob(base64Str);
  // 步骤2:将 ASCII 字符串转回 UTF-8 二进制数据
  const utf8Bytes = new Uint8Array(asciiStr.length);
  for (let i = 0; i < asciiStr.length; i++) {
    utf8Bytes[i] = asciiStr.charCodeAt(i);
  }
  // 步骤3:解码为原字符串
  return new TextDecoder().decode(utf8Bytes);
}