首页 > 代码库 > base64

base64

一.我们来看看,在javascript中如何使用Base64转码
var str = ‘javascript‘;

window.btoa(str)
//转码结果 "amF2YXNjcmlwdA=="

window.atob("amF2YXNjcmlwdA==")
//解码结果 "javascript"
二.对于转码来说,Base64转码的对象只能是字符串,因此来说,对于其他数据还有这一定的局限性,在此特别需要注意的是对Unicode转码。
var str = "China,中国"
window.btoa(str)
Uncaught DOMException: Failed to execute ‘btoa‘ on ‘Window‘: The string to be encoded contains characters outside of the Latin1 range.
很明显,这种方式是不行的,那么如何让他支持汉字呢,这就要使用window.encodeURIComponent和window.decodeURIComponent
var str = "China,中国";

window.btoa(window.encodeURIComponent(str))
//"Q2hpbmElRUYlQkMlOEMlRTQlQjglQUQlRTUlOUIlQkQ="

window.decodeURIComponent(window.atob(‘Q2hpbmElRUYlQkMlOEMlRTQlQjglQUQlRTUlOUIlQkQ=‘))
//"China,中国"

 


var string = ‘Hello World!‘;
console.log(btoa(string)) // "SGVsbG8gV29ybGQh"
console.log(atob(‘SGVsbG8gV29ybGQh‘)) // "Hello World!"

function b64Encode(str) {
return btoa(encodeURIComponent(str));
}

function b64Decode(str) {
return decodeURIComponent(atob(str));
}
console.log(b64Encode(‘Hello World! 你好!‘))
console.log(b64Decode(‘SGVsbG8lMjBXb3JsZCElMjAlRTQlQkQlQTAlRTUlQTUlQkQlRUYlQkMlODE=‘))

 

 

 

/*
*base64编码
* */
/* function base64encode(str) {
var out, i, len;
var c1, c2, c3;
len = str.length;
i = 0;
out = "";
while(i < len) {
c1 = str.charCodeAt(i++) & 0xff;
if(i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt((c1 & 0x3) << 4);
out += "==";
break;
}
c2 = str.charCodeAt(i++);
if(i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt((c2 & 0xF) << 2);
out += "=";
break;
}
c3 = str.charCodeAt(i++);
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
out += base64EncodeChars.charAt(c3 & 0x3F);
}
return out;
}*/

 

 

$.ajax({
url:‘/financepage/finance_public/ImgUpload.ashx‘,
type:‘POST‘,
data:‘Action=Base64Upload&Img=‘+content,
//async:false, //关闭异步
dataType:‘text‘,
//contentType:"application/json; charset=utf-8", //注释掉后就可以传递data了
beforeSend:function(){f_alert2("waitting","图片正在上传中...");},
error:function(XMLHttpRequest, textStatus, errorThrown){
//alert(XMLHttpRequest+" , "+textStatus+" , "+errorThrown)
f_alert2("closeWaitting","");
f_alert2("error","上传过程中出现意外错误");
},
success:function(result){
f_alert2("closeWaitting","");
if(result=="false"||result==undefined||result=="none"||result==""){
f_alert2("error","图片上传失败");
}
else{
//alert(result);
parent.parent.document.getElementById(GetURLParam("hiddName").value=http://www.mamicode.com/result);
}
}
});

base64