# js-base64 包含中文的编解码

# 1. 介绍

window.btoa(str)window.atob(str) 只支持 Latin1 字符。 如下

window.btoa('123');  //=> 'MTIz'

window.atob('MTIz'); //=> '123'

window.btoa('张三'); 
/*
  Uncaught InvalidCharacterError: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
      at <anonymous>:1:8
*/

所以安全的做法是使用第三方 base64 库来 编码和解码字符串。

js-base64 支持 utf8 字符的 base64 编解码

# 2. 使用

import { Base64 } from 'js-base64';

let latin = 'dankogai';
let utf8  = '小飼弾'
let u8s   =  new Uint8Array([100,97,110,107,111,103,97,105]);

Base64.encode(latin);             // ZGFua29nYWk=
Base64.encode(latin, true);       // ZGFua29nYWk skips padding
Base64.encodeURI(latin);          // ZGFua29nYWk

Base64.btoa(latin);               // ZGFua29nYWk=
Base64.btoa(utf8);                // raises exception

Base64.fromUint8Array(u8s);       // ZGFua29nYWk=
Base64.fromUint8Array(u8s, true); // ZGFua29nYW which is URI safe

Base64.encode(utf8);              // 5bCP6aO85by+
Base64.encode(utf8, true)         // 5bCP6aO85by-
Base64.encodeURI(utf8);           // 5bCP6aO85by-

# 3. 参考

  • https://www.npmjs.com/package/js-base64
本章目录