使用Javascript的atob解码base64不能正确解码utf-8字符串

使用Javascript的atob解码base64不能正确解码utf-8字符串

我正在使用Javascript window.atob()函数来解码base64编码的字符串(特别是GitHub API中的base64编码内容)。问题是我得到了ASCII编码的字符(â¢而不是)。如何正确处理传入的base64编码流,以便将其解码为utf-8?



Smart猫小萌
浏览 1779回答 3
3回答

一只名叫tom的猫

如果将字符串视为字节更多是你的事情,你可以使用以下函数function u_atob(ascii) {&nbsp; &nbsp; return Uint8Array.from(atob(ascii), c => c.charCodeAt(0));}function u_btoa(buffer) {&nbsp; &nbsp; var binary = [];&nbsp; &nbsp; var bytes = new Uint8Array(buffer);&nbsp; &nbsp; for (var i = 0, il = bytes.byteLength; i < il; i++) {&nbsp; &nbsp; &nbsp; &nbsp; binary.push(String.fromCharCode(bytes[i]));&nbsp; &nbsp; }&nbsp; &nbsp; return btoa(binary.join(''));}// example, it works also with astral plane characters such as '?'var encodedString = new TextEncoder().encode('✓');var base64String = u_btoa(encodedString);console.log('✓' === new TextDecoder().decode(u_atob(base64String)))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript