js中base64编码问题

最近遇到了一个比较奇葩的问题,字符串-->base64,但是里边还涉及到了gbk编码问题,代码如下:

var content_base64 = "CgkJCgkJCQk8Y29uZGl0aW9ucyB0eXBlPSJBTkQiPgoJCQkJCTxzeXNDb25kaXRpb25zIHR5cGU9Inx8Ij4KCQkJCQk8c3lzQ29uZGl0aW9uIG5hbWU9ItDCzsS1tSIgZXhwcmVzc2lvbj0iS0dselRtVjNSRzlqS0NrcElBPT0iLz4KCQkJCQk8c3lzQ29uZGl0aW9uIG5hbWU9IrWxx7C0psDtyMsiIGV4cHJlc3Npb249IktHbHpRM1Z5VlhObGNpZ3BLU0E9Ii8+CgkJCQkJPC9zeXNDb25kaXRpb25zPgoJCQkJPC9jb25kaXRpb25zPgoJCQk=";

var arrayBuffer = _base64ToArrayBuffer(content_base64);

var content = new TextDecoder("gbk").decode(arrayBuffer);

console.log(content);


function _base64ToArrayBuffer(base64) {

    var binary_string =  window.atob(base64);

    var len = binary_string.length;

    var bytes = new Uint8Array( len );

    for (var i = 0; i < len; i++)        {

        bytes[i] = binary_string.charCodeAt(i);

    }

    return bytes.buffer;

}


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 );

}

https://img3.mukewang.com/5ca066e50001b0d108000275.jpg

怎么把字符串再转回base64(gbk编码格式)???

紫衣仙女
浏览 476回答 1
1回答

一只甜甜圈

反过来就好啦var arrayBuffer = new TextEncoder("gbk").encode(content);var content_base64 =_arrayBufferToBase64(arrayBuffer)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript