JavaScript中是否有任何方法可以用来编码和解码使用base64编码的字符串?
当前回答
PHP .js项目有很多PHP函数的JavaScript实现。包括Base64_encode和base64_decode。
其他回答
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编码
不管怎样,我从其他答案中得到了启发,写了一个小实用程序,调用特定于平台的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"); } }
短而快速的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;
}
除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();
前端:上面的解决方案很好,但后端很快……
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'
推荐文章
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?
- 如何为其他域设置cookie
- 如何减去日期/时间在JavaScript?
- 如何检测“搜索”HTML5输入的清除?
- 字符串中的单词大写
- 返回一个正则表达式匹配()在Javascript的位置?
- Ajax成功事件不工作
- 为什么JavaScript中弃用arguments.callee.caller属性?
- 在typescript中一直使用。tsx而不是。ts有什么缺点吗?
- 如何在Angular.js中配置不同的环境?