首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >客户端Javascript中的Base64编码和解码

客户端Javascript中的Base64编码和解码
EN

Stack Overflow用户
提问于 2010-05-12 23:25:01
回答 13查看 803.7K关注 0票数 320

JavaScript中有什么方法可以用来对使用base64编码的字符串进行编码和解码吗?

EN

回答 13

Stack Overflow用户

发布于 2014-09-15 10:49:31

Internet Explorer 10+

代码语言:javascript
复制
// 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!"

跨浏览器

Re-written and modularized UTF-8 and Base64 Javascript Encoding and Decoding Libraries / Modules for AMD, CommonJS, Nodejs and Browsers. Cross-browser compatible.

使用Node.js

下面是在Node.js中将普通文本编码为base64的方法:

代码语言:javascript
复制
//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编码的字符串:

代码语言:javascript
复制
var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();

使用Dojo.js

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

代码语言:javascript
复制
var str = dojox.encoding.base64.encode(myByteArray);

要对Base64编码的字符串进行解码:

代码语言:javascript
复制
var bytes = dojox.encoding.base64.decode(str)

bower安装angular-base64

代码语言:javascript
复制
<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

票数 88
EN

Stack Overflow用户

发布于 2011-01-15 21:11:38

在基于Gecko/WebKit的浏览器(火狐、Chrome和Safari)和Opera中,你可以使用btoa()atob()

原始答案:How can you encode a string to Base64 in JavaScript?

票数 67
EN

Stack Overflow用户

发布于 2013-02-22 12:01:13

这是Sniper的帖子的加密版。它假定没有回车的格式良好的base64字符串。这个版本消除了几个循环,添加了雅罗斯拉夫的&0xff修复,消除了拖尾空值,以及一些代码高尔夫。

代码语言:javascript
复制
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;
};
票数 45
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2820249

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档