Home >Web Front-end >JS Tutorial >How to Efficiently Convert an ArrayBuffer to a Base64 String?

How to Efficiently Convert an ArrayBuffer to a Base64 String?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-19 10:29:14705browse

How to Efficiently Convert an ArrayBuffer to a Base64 String?

Convert an ArrayBuffer to Base64-Encoded Strings

To efficiently transmute an ArrayBuffer into a base64 string for multipart posting, leverage this native code snippet:

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

While providing an efficient native solution, consider using faster non-native implementations like this one: https://gist.github.com/958841.

Performance comparisons demonstrate a notable speed advantage for non-native methods, as highlighted in benchmarks:

  • jsperf.com/encoding-xhr-image-data/6
  • jsben.ch/wnaZC

The above is the detailed content of How to Efficiently Convert an ArrayBuffer to a Base64 String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn