我需要一个有效的(读本机)方法来转换一个ArrayBuffer到一个base64字符串,这需要在一个多部分的帖子上使用。
当前回答
如果你可以添加一个库,base64-arraybuffer:
yarn add base64-arraybuffer
然后:
encode(buffer) -将ArrayBuffer编码为base64字符串 decode(str) -解码base64字符串到ArrayBuffer
其他回答
在浏览器中建议的解决方案与btoa似乎很好。 但是在Node.js中btoa是不推荐使用的
建议使用buffer.toString(encoding)
like
const myString = buffer.toString("base64")
我使用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)
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://gist.github.com/958841 参见http://jsperf.com/encoding-xhr-image-data/6
更新的基准测试:https://jsben.ch/wnaZC
这对我来说很有效:
var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer)));
在ES6中,语法稍微简单一些:
const base64String = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));
正如评论中指出的,当ArrayBuffer较大时,此方法可能会在某些浏览器中导致运行时错误。确切的大小限制在任何情况下都取决于实现。
这招对我很管用:
Buffer.from(myArrayBuffer).toString("base64");
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔