我需要一个有效的(读本机)方法来转换一个ArrayBuffer到一个base64字符串,这需要在一个多部分的帖子上使用。
当前回答
在我身边,使用Chrome导航器,我必须使用DataView()来读取arrayBuffer
function _arrayBufferToBase64( tabU8A ) {
var binary = '';
let lecteur_de_donnees = new DataView(tabU8A);
var len = lecteur_de_donnees.byteLength;
var chaine = '';
var pos1;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( lecteur_de_donnees.getUint8( i ) );
}
chaine = window.btoa( binary )
return chaine;}
其他回答
我使用TextDecode api将其转换为普通文本,然后将其转换为Base64
const uint = new Uint8Array([ 73, 32, 108, 111, 118, 101, 32, 121, 111, 117 ]).buffer
const decoder = new TextDecoder()
const decodedText = decoder.decode(uint)
const base64Code = btoa(decodedText)
这招对我很管用:
Buffer.from(myArrayBuffer).toString("base64");
还有另一种异步方式使用Blob和FileReader。
我没有测试性能。但这是一种不同的思维方式。
function arrayBufferToBase64( buffer, callback ) {
var blob = new Blob([buffer],{type:'application/octet-binary'});
var reader = new FileReader();
reader.onload = function(evt){
var dataurl = evt.target.result;
callback(dataurl.substr(dataurl.indexOf(',')+1));
};
reader.readAsDataURL(blob);
}
//example:
var buf = new Uint8Array([11,22,33]);
arrayBufferToBase64(buf, console.log.bind(console)); //"CxYh"
在浏览器中建议的解决方案与btoa似乎很好。 但是在Node.js中btoa是不推荐使用的
建议使用buffer.toString(encoding)
like
const myString = buffer.toString("base64")
使用uint8-to-b64包在浏览器和Node.js中进行编码/解码