客户端 Javascript 中的 Base64 编码和解码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2820249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Base64 encoding and decoding in client-side Javascript
提问by Mo.
Are there any methods in JavaScript that could be used to encode and decode a string using base64 encoding?
JavaScript 中是否有任何方法可用于使用 base64 编码对字符串进行编码和解码?
采纳答案by Ranhiru Jude Cooray
Some browsers such as Firefox, Chrome, Safari, Opera and IE10+ can handle Base64 natively. Take a look at this Stackoverflow question. It's using btoa()and atob()functions.
一些浏览器,如 Firefox、Chrome、Safari、Opera 和 IE10+ 可以原生处理 Base64。看看这个Stackoverflow 问题。它正在使用btoa()和atob()功能。
For server-side JavaScript (Node), you can use Buffers to decode.
对于服务端 JavaScript(Node),可以使用Buffers 进行解码。
If you are going for a cross-browser solution, there are existing libraries like CryptoJSor code like:
如果您要跨浏览器解决方案,可以使用现有的库,如CryptoJS或代码,如:
http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html
http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html
With the latter, you need to thoroughly test the function for cross browser compatibility. And error has already been reported.
对于后者,您需要彻底测试跨浏览器兼容性的功能。并且已经报告了错误。
回答by nyuszika7h
In Gecko/WebKit-based browsers (Firefox, Chrome and Safari) and Opera, you can use btoa()and atob().
在基于 Gecko/WebKit 的浏览器(Firefox、Chrome 和 Safari)和 Opera 中,您可以使用btoa()和atob()。
Original answer: How can you encode a string to Base64 in JavaScript?
回答by davidcondrey
Internet Explorer 10+
浏览器 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!"
Cross-Browser
跨浏览器
为 AMD、CommonJS、Nodejs 和浏览器重写和模块化 UTF-8 和 Base64 Javascript 编码和解码库/模块。跨浏览器兼容。
with Node.js
使用 Node.js
Here is how you encode normal text to base64 in 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 = new Buffer('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');
And here is how you decode base64 encoded strings:
以下是解码 base64 编码字符串的方法:
var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();
with Dojo.js
使用 Dojo.js
To encode an array of bytes using dojox.encoding.base64:
使用 dojox.encoding.base64 对字节数组进行编码:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a base64-encoded string:
要解码 base64 编码的字符串:
var bytes = dojox.encoding.base64.decode(str)
bower install angular-base64
凉亭安装 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=');
}]);
But How?
但是如何?
If you would like to learn more about how base64 is encoded in general, and in JavaScript in-particular, I would recommend this article: Computer science in JavaScript: Base64 encoding
如果您想了解更多关于 base64 是如何编码的,特别是在 JavaScript 中,我会推荐这篇文章: JavaScript 中的计算机科学:Base64 编码
回答by broc.seib
Here is a tightened up version of Sniper's post. It presumes well formed base64 string with no carriage returns. This version eliminates a couple of loops, adds the &0xfffix from Yaroslav, eliminates trailing nulls, plus a bit of code golf.
这是狙击手帖子的加强版。它假定格式良好的 base64 字符串没有回车。这个版本消除了几个循环,添加了&0xffYaroslav的修复,消除了尾随空值,加上一些代码高尔夫。
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;
};
回答by Sniper
Short and fast Base64 JavaScript Decode Function without Failsafe:
没有故障安全的简短而快速的 Base64 JavaScript 解码函数:
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;
}
回答by PPB
function b64_to_utf8( str ) {
return decodeURIComponent(escape(window.atob( str )));
}
回答by ceejayoz
回答by nickl-
Did someone say code golf? =)
有人说代码高尔夫吗?=)
The following is my attempt at improving my handicap while catching up with the times. Supplied for your convenience.
以下是我在赶上时代的同时改善自己的障碍的尝试。为您提供方便。
function decode_base64(s) {
var b=l=0, r='',
m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
s.split('').forEach(function (v) {
b=(b<<6)+m.indexOf(v); l+=6;
if (l>=8) r+=String.fromCharCode((b>>>(l-=8))&0xff);
});
return r;
}
What I was actually after was an asynchronous implementation and to my surprise it turns out forEachas opposed to JQuery's $([]).eachmethod implementation is very much synchronous.
我实际上追求的是异步实现,令我惊讶的是forEach,与 JQuery 的$([]).each方法实现相反,它是非常同步的。
If you also had such crazy notions in mind a 0 delay window.setTimeoutwill run the base64 decode asynchronously and execute the callback function with the result when done.
如果您也有这种疯狂的想法,那么 0 延迟window.setTimeout将异步运行 base64 解码,并在完成后使用结果执行回调函数。
function decode_base64_async(s, cb) {
setTimeout(function () { cb(decode_base64(s)); }, 0);
}
@Toothbrush suggested "index a string like an array", and get rid of the split. This routine seems really odd and not sure how compatible it will be, but it does hit another birdie so lets have it.
@Toothbrush 建议“索引一个像数组一样的字符串”,并去掉split. 这个例程看起来很奇怪,不确定它的兼容性如何,但它确实击中了另一只小鸟,所以让我们开始吧。
function decode_base64(s) {
var b=l=0, r='',
m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
[].forEach.call(s, function (v) {
b=(b<<6)+m.indexOf(v); l+=6;
if (l>=8) r+=String.fromCharCode((b>>>(l-=8))&0xff);
});
return r;
}
While trying to find more information on JavaScript string as array I stumbled on this pro tip using a /./gregex to step through a string. This reduces the code size even more by replacing the string in place and eliminating the need of keeping a return variable.
在尝试查找有关 JavaScript 字符串作为数组的更多信息时,我偶然发现了这个使用/./g正则表达式单步执行字符串的专业提示。通过替换字符串并消除保留返回变量的需要,这进一步减少了代码大小。
function decode_base64(s) {
var b=l=0,
m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
return s.replace(/./g, function (v) {
b=(b<<6)+m.indexOf(v); l+=6;
return l<8?'':String.fromCharCode((b>>>(l-=8))&0xff);
});
}
If however you were looking for something a little more traditional perhaps the following is more to your taste.
但是,如果您正在寻找更传统的东西,那么以下内容可能更符合您的口味。
function decode_base64(s) {
var b=l=0, r='', s=s.split(''), i,
m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
for (i in s) {
b=(b<<6)+m.indexOf(s[i]); l+=6;
if (l>=8) r+=String.fromCharCode((b>>>(l-=8))&0xff);
}
return r;
}
I didn't have the trailing null issue so this was removed to remain under par but it should easily be resolved with a trim()or a trimRight()if you'd prefer, should this pose a problem for you.
我没有尾随空问题,因此已将其删除以保持低于标准杆,但如果您愿意,应该可以轻松地使用 atrim()或 a解决,这trimRight()是否会给您带来问题。
ie.
IE。
return r.trimRight();
Note:
笔记:
The result is an ascii byte string, if you need unicode the easiest is to escapethe byte string which can then be decoded with decodeURIComponentto produce the unicode string.
结果是一个 ascii 字节字符串,如果您需要 unicode,最简单的方法是对escape字节字符串进行解码decodeURIComponent以生成 unicode 字符串。
function decode_base64_usc(s) {
return decodeURIComponent(escape(decode_base64(s)));
}
Since escapeis being deprecated we could change our function to support unicode directly without the need for escapeor String.fromCharCodewe can produce a %escaped string ready for URI decoding.
由于escape已被弃用,我们可以更改我们的函数以直接支持 unicode,而不需要escape或者String.fromCharCode我们可以生成一个%准备用于 URI 解码的转义字符串。
function decode_base64(s) {
var b=l=0,
m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
return decodeURIComponent(s.replace(/./g, function (v) {
b=(b<<6)+m.indexOf(v); l+=6;
return l<8?'':'%'+(0x100+((b>>>(l-=8))&0xff)).toString(16).slice(-2);
}));
}
nJoy!
快乐!
回答by Scott Carter
I have tried the Javascript routines at phpjs.org and they have worked well.
我在 phpjs.org 尝试过 Javascript 例程,它们运行良好。
I first tried the routines suggested in the chosen answer by Ranhiru Cooray - http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html
我首先尝试了 Ranhiru Cooray 在所选答案中建议的例程 - http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html
I found that they did not work in all circumstances. I wrote up a test case where these routines fail and posted them to GitHub at:
我发现它们并非在所有情况下都有效。我写了一个测试用例,其中这些例程失败并将它们发布到 GitHub 上:
https://github.com/scottcarter/base64_javascript_test_data.git
https://github.com/scottcarter/base64_javascript_test_data.git
I also posted a comment to the blog post at ntt.cc to alert the author (awaiting moderation - the article is old so not sure if comment will get posted).
我还在 ntt.cc 的博客文章中发表了评论以提醒作者(等待审核 - 文章较旧,因此不确定是否会发布评论)。

