JavaScript中是否有任何方法可以用来编码和解码使用base64编码的字符串?


当前回答

以下是Sniper的文章的压缩版。它假定格式良好的base64字符串,没有回车。这个版本消除了几个循环,从Yaroslav中添加了&0xff修复,消除了尾随null,再加上一些代码golf。

decodeBase64 = function(s) {
    var e={},i,b=0,c,x,l=0,a,r='',w=String.fromCharCode,L=s.length;
    var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for(i=0;i<64;i++){e[A.charAt(i)]=i;}
    for(x=0;x<L;x++){
        c=e[s.charAt(x)];b=(b<<6)+c;l+=6;
        while(l>=8){((a=(b>>>(l-=8))&0xff)||(x<(L-2)))&&(r+=w(a));}
    }
    return r;
};

其他回答

一些浏览器,如Firefox, Chrome, Safari, Opera和IE10+可以原生处理Base64。看看这个Stackoverflow问题。它使用btoa()和atob()函数。

对于服务器端JavaScript (Node),可以使用buffer进行解码。

如果你想要一个跨浏览器的解决方案,有像CryptoJS这样的现有库或如下代码:

http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html(存档)

对于后者,您需要彻底测试该函数的跨浏览器兼容性。错误已经报告过了。

对于没有atob方法的JavaScripts框架,如果你不想导入外部库,这是一个简短的函数。

它将获得一个包含Base64编码值的字符串,并将返回一个解码后的字节数组(其中字节数组表示为数字数组,其中每个数字都是0到255之间的整数)。

function fromBase64String(str) {
    var alpha = 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var value = [];
    var index = 0;
    var destIndex  = 0;
    var padding = false;
    while (true) {

        var first  = getNextChr(str, index, padding, alpha);
        var second = getNextChr(str, first .nextIndex, first .padding, alpha);
        var third  = getNextChr(str, second.nextIndex, second.padding, alpha);
        var fourth = getNextChr(str, third .nextIndex, third .padding, alpha);

        index = fourth.nextIndex;
        padding = fourth.padding;

        // ffffffss sssstttt ttffffff
        var base64_first  = first.code  == null ? 0 : first.code;
        var base64_second = second.code == null ? 0 : second.code;
        var base64_third  = third.code  == null ? 0 : third.code;
        var base64_fourth = fourth.code == null ? 0 : fourth.code;

        var a = (( base64_first << 2) & 0xFC ) | ((base64_second>>4) & 0x03);
        var b = (( base64_second<< 4) & 0xF0 ) | ((base64_third >>2) & 0x0F);
        var c = (( base64_third << 6) & 0xC0 ) | ((base64_fourth>>0) & 0x3F);

        value [destIndex++] = a;
        if (!third.padding) {
            value [destIndex++] = b;
        } else {
            break;
        }
        if (!fourth.padding) {
            value [destIndex++] = c;
        } else {
            break;
        }
        if (index >= str.length) {
            break;
        }
    }
    return value;
}

function getNextChr(str, index, equalSignReceived, alpha) {
    var chr = null;
    var code = 0;
    var padding = equalSignReceived;
    while (index < str.length) {
        chr = str.charAt(index);
        if (chr == " " || chr == "\r" || chr == "\n" || chr == "\t") {
            index++;
            continue;
        }
        if (chr == "=") {
            padding = true;
        } else {
            if (equalSignReceived) {
                throw new Error("Invalid Base64 Endcoding character \"" 
                    + chr + "\" with code " + str.charCodeAt(index) 
                    + " on position " + index 
                    + " received afer an equal sign (=) padding "
                    + "character has already been received. "
                    + "The equal sign padding character is the only "
                    + "possible padding character at the end.");
            }
            code = alpha.indexOf(chr);
            if (code == -1) {
                throw new Error("Invalid Base64 Encoding character \"" 
                    + chr + "\" with code " + str.charCodeAt(index) 
                    + " on position " + index + ".");
            }
        }
        break;
    }
    return { character: chr, code: code, padding: padding, nextIndex: ++index};
}

使用的资源:RFC-4648第4节

PHP .js项目有很多PHP函数的JavaScript实现。包括Base64_encode和base64_decode。

以下是Sniper的文章的压缩版。它假定格式良好的base64字符串,没有回车。这个版本消除了几个循环,从Yaroslav中添加了&0xff修复,消除了尾随null,再加上一些代码golf。

decodeBase64 = function(s) {
    var e={},i,b=0,c,x,l=0,a,r='',w=String.fromCharCode,L=s.length;
    var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for(i=0;i<64;i++){e[A.charAt(i)]=i;}
    for(x=0;x<L;x++){
        c=e[s.charAt(x)];b=(b<<6)+c;l+=6;
        while(l>=8){((a=(b>>>(l-=8))&0xff)||(x<(L-2)))&&(r+=w(a));}
    }
    return r;
};

不管怎样,我从其他答案中得到了启发,写了一个小实用程序,调用特定于平台的api,从Node.js或浏览器中普遍使用:

/** * Encode a string of text as base64 * * @param data The string of text. * @returns The base64 encoded string. */ function encodeBase64(data: string) { if (typeof btoa === "function") { return btoa(data); } else if (typeof Buffer === "function") { return Buffer.from(data, "utf-8").toString("base64"); } else { throw new Error("Failed to determine the platform specific encoder"); } } /** * Decode a string of base64 as text * * @param data The string of base64 encoded text * @returns The decoded text. */ function decodeBase64(data: string) { if (typeof atob === "function") { return atob(data); } else if (typeof Buffer === "function") { return Buffer.from(data, "base64").toString("utf-8"); } else { throw new Error("Failed to determine the platform specific decoder"); } }