JavaScript字节流与Base64

1、字节流转Base64

function arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}

2、Base64转Blob对象

function convertBase64UrlToBlob(base64){
    var type =base64.split(",")[0].match(/:(.*?);/)[1];    
    var bytes=window.atob(base64.split(',')[1]);
    var ab = new ArrayBuffer(bytes.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
    }
    return new Blob( [ab] , {type :type});
}

发表评论