JavaScript中是否有任何方法可以用来编码和解码使用base64编码的字符串?
当前回答
现代浏览器有内置的javascript函数用于Base64编码btoa()和解码atob()。有关旧版本浏览器支持的更多信息:https://caniuse.com/?search=atob
但是,请注意atob和btoa函数仅适用于ASCII字符集。 如果你需要Base64函数的UTF-8字符集,你可以这样做:
function base64_encode(s) {
return btoa(unescape(encodeURIComponent(s)));
}
function base64_decode(s) {
return decodeURIComponent(escape(atob(s)));
}
其他回答
我已经尝试了phpjs.org的Javascript例程,他们工作得很好。
我首先尝试了Ranhiru Cooray给出的答案——http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html
我发现它们并不是在所有情况下都有效。我写了一个测试用例,这些例程失败了,并将它们发布到GitHub:
https://github.com/scottcarter/base64_javascript_test_data.git
我也在ntt的博客上发表了评论。抄送提醒作者(等待审核-文章是旧的,所以不确定是否会张贴评论)。
在基于Gecko/ webkit的浏览器(Firefox、Chrome和Safari)和Opera中,可以使用btoa()和atob()。
原来的答案:如何在JavaScript中将字符串编码为Base64 ?
前端:上面的解决方案很好,但后端很快……
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'
短而快速的Base64 JavaScript解码函数没有Failsafe:
function decode_base64 (s)
{
var e = {}, i, k, v = [], r = '', w = String.fromCharCode;
var n = [[65, 91], [97, 123], [48, 58], [43, 44], [47, 48]];
for (z in n)
{
for (i = n[z][0]; i < n[z][1]; i++)
{
v.push(w(i));
}
}
for (i = 0; i < 64; i++)
{
e[v[i]] = i;
}
for (i = 0; i < s.length; i+=72)
{
var b = 0, c, x, l = 0, o = s.substring(i, i+72);
for (x = 0; x < o.length; x++)
{
c = e[o.charAt(x)];
b = (b << 6) + c;
l += 6;
while (l >= 8)
{
r += w((b >>> (l -= 8)) % 256);
}
}
}
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(存档)
对于后者,您需要彻底测试该函数的跨浏览器兼容性。错误已经报告过了。