HTML5原生支持Base64编码解码

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

该方法仅支持IE10+、chrome、等现代浏览器。

适合用于原生支持的

(function(){
	var Base64 = {
		encode : function(str){
			return window.btoa(unescape(encodeURIComponent(str)));
		},
		decode : function(str){
			return decodeURIComponent(escape(window.atob(str)));
		}
	};
	window.BASE64 = Base64;
})();

旧版本兼容

(function() {
	if (!window.btoa) {
		var a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		window.btoa = function(c) {
			var d = "";
			var m, k, h = "";
			var l, j, g, f = "";
			var e = 0;
			do {
				m = c.charCodeAt(e++);
				k = c.charCodeAt(e++);
				h = c.charCodeAt(e++);
				l = m >> 2;
				j = ((m & 3) << 4) | (k >> 4);
				g = ((k & 15) << 2) | (h >> 6);
				f = h & 63;
				if (isNaN(k)) {
					g = f = 64
				} else {
					if (isNaN(h)) {
						f = 64
					}
				}
				d = d + a.charAt(l) + a.charAt(j) + a.charAt(g) + a.charAt(f);
				m = k = h = "";
				l = j = g = f = ""
			} while (e < c.length);
			return d
		};
		window.atob = function(c) {
			var d = "";
			var m, k, h = "";
			var l, j, g, f = "";
			var e = 0;
			do {
				l = a.indexOf(c.charAt(e++));
				if (l < 0) {
					continue
				}
				j = a.indexOf(c.charAt(e++));
				if (j < 0) {
					continue
				}
				g = a.indexOf(c.charAt(e++));
				if (g < 0) {
					continue
				}
				f = a.indexOf(c.charAt(e++));
				if (f < 0) {
					continue
				}
				m = (l << 2) | (j >> 4);
				k = ((j & 15) << 4) | (g >> 2);
				h = ((g & 3) << 6) | f;
				d += String.fromCharCode(m);
				if (g != 64) {
					d += String.fromCharCode(k)
				}
				if (f != 64) {
					d += String.fromCharCode(h)
				}
				m = k = h = "";
				l = j = g = f = ""
			} while (e < c.length);
			return d
		}
	}
	var b = {
		encode: function(c) {
			return window.btoa(unescape(encodeURIComponent(c)))
		},
		decode: function(c) {
			return decodeURIComponent(escape(window.atob(c)))
		}
	};
	window.BASE64 = b
})();

 

相关链接: https://developer.mozilla.org/zh-CN/docs/Web/API/Window.btoa

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:python开发的简单窗口界面的倒计时界面

下一篇:IOS屏幕旋转