[JS] Base64エンコードとデコードを実現(および中国語文字化け問題)

1. ネイティブ実装

  • JavaScript では、Base64 に関連する 2 つのグローバル メソッドが定義されています。
1. btoa():字符串或二进制值转为 Base64 编码。
2. atob():把 Base64 编码转为原来的字符。
  • 中国語のエンコードが発生した場合は、最初に URI コンポーネントのエンコードを行うか、デコードされたコンテンツを URI デコードする必要があります。
1. encodeURIComponent():结合 btoa 使用
2. decodeURIComponent():结合 atob 使用
  • 例: Base64 エンコード
// btoa() 相当于 window.btoa(),encodeURIComponent 同理
const str = 'test'
const encode = btoa(encodeURIComponent(str))
console.log(encode)	// dGVzdA==
  • 例: Base64 デコード
// atob() 相当于 window.atob(),decodeURIComponent 同理
const str = 'dGVzdA=='
const decode = decodeURIComponent(atob(str))
console.log(decode)	// test
  • 中国語文字化けの処理方法:
const Base64 = {
    
    
    encode(str) {
    
    
        // 首先,我们使用 encodeURIComponent 来获得百分比编码的UTF-8,然后我们将百分比编码转换为原始字节,最后存储到btoa里面
        return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
            function toSolidBytes(match, p1) {
    
    
                return String.fromCharCode(Number('0x' + p1));
            }));
    },
    decode(str) {
    
    
        // 过程:从字节流到百分比编码,再到原始字符串
        return decodeURIComponent(atob(str).split('').map(function (c) {
    
    
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
    }
}
let encoded = Base64.encode("一颗不甘坠落的流星"); 	// "5LiA6aKX5LiN55SY5Z2g6JC955qE5rWB5pif"
let decoded = Base64.decode(encoded); 				// "一颗不甘坠落的流星"

2 番目に、プラグインの実装

  • Base64 プラグイン: codec: に従ってjs-base64、Base64 エンコード形式であるかどうかを判断します。is-base64
npm i js-base64
npm i is-base64
  • プラグインの使用
import isBase64 from 'is-base64';
import {
    
     Base64 } from 'js-base64';

// 封装解码函数
const base64ToStr = (base64Str: string): string => {
    
    
  if (isBase64(base64Str)) {
    
    
    return Base64.decode(base64Str);
  }
  return base64Str;
};
// 封装编码函数
export const strToBase64 = (str: string): string => Base64.encode(str);

console.log(strToBase64('一颗不甘坠落的流星'))	// 5LiA6aKX5LiN55SY5Z2g6JC955qE5rWB5pif
console.log(base64ToStr('5LiA6aKX5LiN55SY5Z2g6JC955qE5rWB5pif'))	// 一颗不甘坠落的流星

おすすめ

転載: blog.csdn.net/qq_45677671/article/details/131070535