JavaScript中有什么方法可以用来对使用base64编码的字符串进行编码和解码吗?
发布于 2014-09-15 10:49:31
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!"
跨浏览器
使用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');
下面是如何解码base64编码的字符串:
var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();
使用Dojo.js
要使用dojox.encoding.base64对字节数组进行编码:
var str = dojox.encoding.base64.encode(myByteArray);
要对Base64编码的字符串进行解码:
var bytes = dojox.encoding.base64.decode(str)
bower安装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,我推荐这篇文章:Computer science in JavaScript: Base64 encoding
发布于 2011-01-15 21:11:38
发布于 2013-02-22 12:01:13
这是Sniper的帖子的加密版。它假定没有回车的格式良好的base64字符串。这个版本消除了几个循环,添加了雅罗斯拉夫的&0xff
修复,消除了拖尾空值,以及一些代码高尔夫。
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;
};
https://stackoverflow.com/questions/2820249
复制相似问题