Home >Web Front-end >JS Tutorial >How to Efficiently Convert ArrayBuffers to Base64 Strings in JavaScript?
Converting ArrayBuffers to Base64 Strings in Native JavaScript
The task at hand is to efficiently convert an ArrayBuffer into a base64-encoded string, a requirement for multipart POST requests.
Native Implementation
The code below provides a native solution:
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); }
This implementation converts the ArrayBuffer to a binary string before applying base64 encoding.
Non-Native Alternative
Although the native implementation is reliable, non-native approaches exist that offer improved performance. One such implementation is found at:
https://gist.github.com/958841
Performance benchmarks indicate that non-native methods can be faster. See:
http://jsperf.com/encoding-xhr-image-data/6
Updated benchmarks:
https://jsben.ch/wnaZC
The above is the detailed content of How to Efficiently Convert ArrayBuffers to Base64 Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!