Mo.*_*Mo. 237 javascript base64
JavaScript中是否有任何方法可用于使用base64编码对字符串进行编码和解码?
Ran*_*ray 187
某些浏览器,如Firefox,Chrome,Safari,Opera和IE10 +本身可以处理Base64.看看这个Stackoverflow问题.它正在使用btoa()和atob()功能.
对于服务器端JavaScript,Node.JS有一个btoa包.
如果您要使用跨浏览器解决方案,可以使用现有的库,如CryptoJS或类似代码:
http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html
对于后者,您需要彻底测试该功能以实现跨浏览器兼容性.并且已经报告了错误.
nyu*_*a7h 62
在基于Gecko/WebKit的浏览器(Firefox,Chrome和Safari)和Opera中,您可以使用btoa()和atob().
原始答案:如何在JavaScript中将字符串编码为Base64?
dav*_*rey 49
// 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!"
Run Code Online (Sandbox Code Playgroud)
为AMD,CommonJS,Nodejs和浏览器重写和模块化UTF-8和Base64 Javascript编码和解码库/模块.跨浏览器兼容.
以下是在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');
Run Code Online (Sandbox Code Playgroud)
以下是解码base64编码字符串的方法:
var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();
Run Code Online (Sandbox Code Playgroud)
使用dojox.encoding.base64编码字节数组:
var str = dojox.encoding.base64.encode(myByteArray);
Run Code Online (Sandbox Code Playgroud)
要解码base64编码的字符串:
var bytes = dojox.encoding.base64.decode(str)
Run Code Online (Sandbox Code Playgroud)
<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=');
}]);
Run Code Online (Sandbox Code Playgroud)
如果您想了解更多关于base64如何编码的信息,特别是在JavaScript中,我会推荐这篇文章: JavaScript中的计算机科学:Base64编码
bro*_*eib 39
这是一个收紧版本的狙击手的帖子.它假设格式良好的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;
};
Run Code Online (Sandbox Code Playgroud)
小智 31
短而快的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;
}
Run Code Online (Sandbox Code Playgroud)
PPB*_*PPB 12
function b64_to_utf8( str ) {
return decodeURIComponent(escape(window.atob( str )));
}Run Code Online (Sandbox Code Playgroud)
有人说代码高尔夫吗?=)
以下是我在追赶时代的同时改善差点的尝试.供您方便使用.
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;
}
Run Code Online (Sandbox Code Playgroud)
我实际上是一个异步实现,令我惊讶的是forEach,与JQuery的$([]).each方法实现相反,它是非常同步的.
如果您还有这样的疯狂概念,0延迟window.setTimeout将异步运行base64解码并在完成后执行回调函数.
function decode_base64_async(s, cb) {
setTimeout(function () { cb(decode_base64(s)); }, 0);
}
Run Code Online (Sandbox Code Playgroud)
@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;
}
Run Code Online (Sandbox Code Playgroud)
在尝试查找有关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);
});
}
Run Code Online (Sandbox Code Playgroud)
如果您正在寻找更传统的东西,或许以下更符合您的口味.
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;
}
Run Code Online (Sandbox Code Playgroud)
我没有尾随空问题,所以这被删除以保持低于标准但是如果你喜欢,它应该很容易用a trim()或a 解决,trimRight()如果这对你造成问题.
即.
return r.trimRight();
Run Code Online (Sandbox Code Playgroud)
结果是一个ascii字节字符串,如果你需要unicode,最简单的是escape字节字符串,然后可以用它来解码decodeURIComponent以产生unicode字符串.
function decode_base64_usc(s) {
return decodeURIComponent(escape(decode_base64(s)));
}
Run Code Online (Sandbox Code Playgroud)
由于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);
}));
}
Run Code Online (Sandbox Code Playgroud)
的nJoy!
现代浏览器具有用于 Base64 编码btoa()和解码atob() 的内置 javascript 函数。有关旧浏览器版本支持的更多信息:https : //caniuse.com/?search=atob
但是,请注意atob和btoa函数仅适用于 ASCII 字符集。如果您需要 UTF-8 字符集的 Base64 函数,您可以使用:
function base64_encode(s) {
return btoa(unescape(encodeURIComponent(s)));
}
function base64_decode(s) {
return decodeURIComponent(escape(atob(s)));
}
Run Code Online (Sandbox Code Playgroud)
我在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.cc的博客文章上发表评论,提醒作者(等待审核 - 文章已经过时,所以不确定是否会发布评论).
对于它的价值,我从其他答案中得到启发,并编写了一个小实用程序,它调用特定于平台的 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");
}
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
589340 次 |
| 最近记录: |