Base64 是將二進制數據編碼為 ASCII 字符串的常用方案。現代瀏覽器提供原生 btoa/atob,但僅支持 ASCII。本文提供完整的 UTF-8 兼容封裝,並對比原生 API 差異。
// 編碼
var encoded = btoa('Hello World'); // "SGVsbG8gV29ybGQ="
// 解碼
var decoded = atob(encoded); // "Hello World"
// 中文會報錯:Uncaught DOMException
// btoa('你好'); // 錯誤
var Base64 = {
// 編碼:字符串 -> UTF-8 字節 -> Base64
encode: function(str) {
// 先轉 UTF-8 字節序列
var utf8Bytes = unescape(encodeURIComponent(str));
return btoa(utf8Bytes);
},
// 解碼:Base64 -> UTF-8 字節 -> 字符串
decode: function(base64Str) {
var utf8Bytes = atob(base64Str);
return decodeURIComponent(escape(utf8Bytes));
}
};
// 測試
var str = '你好,世界!😀';
var encoded = Base64.encode(str); // "5L2g5aW977yM5Lit5paH77yB8J+YgA=="
var decoded = Base64.decode(encoded); // "你好,世界!😀"
console.log(encoded, decoded);
encodeURIComponent 將字符串按 UTF-8 編碼為 %XX 格式。unescape 將 %XX 轉為對應字符(實際得到 Latin1 字符串,每字符對應一字節)。btoa 對這個「偽 Latin1」字符串進行 Base64 編碼。atob → escape(Latin1 轉 %XX) → decodeURIComponent(UTF-8 解碼)。// Buffer 原生支持
var encoded = Buffer.from('你好').toString('base64');
var decoded = Buffer.from(encoded, 'base64').toString('utf8');
大數據量場景請使用 FileReader.readAsDataURL 或 Streams API,避免內存溢出。