
window.atob(),window.btoa()方法可以对字符串精选base64编码和解码,但是有些环境比如nuxt的服务端环境没法使用window,所以需要自己实现一个base64的编码解码功能,下面是原生js实现该功能,可以作为一个常用工具使用。
// private property
let _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // private method for UTF-8 encoding
function _utf8_encode (string) {
string = string.replace(/\r\n/g,"\n");
let utftext = "";
for (let n = ; n < string.length; n++) {
let c = string.charCodeAt(n);
if (c < ) {
utftext += String.fromCharCode(c);
} else if((c > ) && (c < )) {
utftext += String.fromCharCode((c >> ) | );
utftext += String.fromCharCode((c & ) | );
} else {
utftext += String.fromCharCode((c >> ) | );
utftext += String.fromCharCode(((c >> ) & ) | );
utftext += String.fromCharCode((c & ) | );
} }
return utftext;
} // private method for UTF-8 decoding
function _utf8_decode (utftext) {
let string = "";
let i = ;
let c = ;
let c1 = ;
let c2 = ;
let c3 = ;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < ) {
string += String.fromCharCode(c);
i++;
} else if((c > ) && (c < )) {
c2 = utftext.charCodeAt(i+);
string += String.fromCharCode(((c & ) << ) | (c2 & ));
i += ;
} else {
c2 = utftext.charCodeAt(i+);
c3 = utftext.charCodeAt(i+);
string += String.fromCharCode(((c & ) << ) | ((c2 & ) << ) | (c3 & ));
i += ;
}
}
return string;
} // public method for encoding
export const encode = (input) => {
let output = "";
let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
let i = ;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> ;
enc2 = ((chr1 & ) << ) | (chr2 >> );
enc3 = ((chr2 & ) << ) | (chr3 >> );
enc4 = chr3 & ;
if (isNaN(chr2)) {
enc3 = enc4 = ;
} else if (isNaN(chr3)) {
enc4 = ;
}
output = output +
_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
}
return output;
} // public method for decoding
export const decode = (input) => {
let output = "";
let chr1, chr2, chr3;
let enc1, enc2, enc3, enc4;
let i = ;
input = input.replace(/[^A-Za-z0-\+\/\=]/g, "");
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << ) | (enc2 >> );
chr2 = ((enc2 & ) << ) | (enc3 >> );
chr3 = ((enc3 & ) << ) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != ) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != ) {
output = output + String.fromCharCode(chr3);
}
}
output = _utf8_decode(output);
return output;
}
当然github上还有很多比较好的base64转码解码插件,可以自行查找