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


当前回答

不管怎样,我从其他答案中得到了启发,写了一个小实用程序,调用特定于平台的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"); } }

其他回答

前端:上面的解决方案很好,但后端很快……

NodeJS -不弃用

使用Buffer.from。

> inBase64 = Buffer.from('plain').toString('base64')
'cGxhaW4='

> // DEPRECATED //
> new Buffer(inBase64, 'base64').toString()
'plain'
> (node:1188987) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(Use `node --trace-deprecation ...` to show where the warning was created)

// Works //
> Buffer.from(inBase64, 'base64').toString()
'plain'

Internet Explorer 10+

// Define the string
var string = 'Hello World!';

// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

跨浏览器

重写和模块化的UTF-8和Base64 Javascript编码和解码库/模块,用于AMD, CommonJS, Nodejs和浏览器。跨浏览器兼容的。


用node . js

下面是在Node.js中如何将普通文本编码为base64:

//Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter. 
// Default is utf8, possible encoding types are ascii, utf8, ucs2, base64, binary, and hex
var b = Buffer.from('JavaScript');
// If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
// We can make it convert to other formats by passing the encoding type to toString().
var s = b.toString('base64');

下面是解码base64编码字符串的方法:

var b = Buffer.from('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();

. js和

使用dojox.encoding.base64对字节数组进行编码:

var str = dojox.encoding.base64.encode(myByteArray);

解码base64编码的字符串:

var bytes = dojox.encoding.base64.decode(str)

安装angular-base64

<script src="bower_components/angular-base64/angular-base64.js"></script>

angular
    .module('myApp', ['base64'])
    .controller('myController', [

    '$base64', '$scope', 
    function($base64, $scope) {
    
        $scope.encoded = $base64.encode('a string');
        $scope.decoded = $base64.decode('YSBzdHJpbmc=');
}]);

但如何?

如果你想了解更多关于base64是如何编码的,特别是在JavaScript中,我推荐这篇文章:JavaScript中的计算机科学:base64编码

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

除acsi或iso-8859-1以外的编码的Base64 Win-1251解码。

结果,我在这里看到的所有脚本都将西里尔Base64转换为iso-8859-1编码。奇怪的是没有人注意到这一点。

因此,要恢复西里尔字母,只需将文本从iso-8859-1转换为windows-1251即可。

我认为其他语言也是如此。只要把Cyrilic window -1251改成你的。

…感谢Der Hochstapler的代码,我从他的评论中了解到…过度评论,这有点不寻常。

JScript代码(仅适用于Windows桌面)(ActiveXObject) - 1251文件编码

decode_base64=function(f){var g={},b=65,d=0,a,c=0,h,e="",k=String.fromCharCode,l=f.length;for(a="";91>b;)a+=k(b++);a+=a.toLowerCase()+"0123456789+/";for(b=0;64>b;b++)g[a.charAt(b)]=b;for(a=0;a<l;a++)for(b=g[f.charAt(a)],d=(d<<6)+b,c+=6;8<=c;)((h=d>>>(c-=8)&255)||a<l-2)&&(e+=k(h));return e};
sDOS2Win = function(sText, bInsideOut) {
    var aCharsets = ["iso-8859-1", "windows-1251"];
    sText += "";
    bInsideOut = bInsideOut ? 1 : 0;
    with (new ActiveXObject("ADODB.Stream")) { //http://www.w3schools.com/ado/ado_ref_stream.asp
        type = 2; //Binary 1, Text 2 (default) 
        mode = 3; //Permissions have not been set 0,  Read-only 1,  Write-only 2,  Read-write 3,  
        //Prevent other read 4,  Prevent other write 8,  Prevent other open 12,  Allow others all 16
        charset = aCharsets[bInsideOut]; 
        open();
        writeText(sText);
        position = 0;
        charset = aCharsets[1 - bInsideOut];
        return readText();
    }
}
var base64='0PPx8ero5SDh8+ru4uroIQ=='
text = sDOS2Win(decode_base64(base64), false );
WScript.Echo(text)
var x=WScript.StdIn.ReadLine();

一些浏览器,如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(存档)

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