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

How Can I Efficiently Convert an ArrayBuffer to a Base64 String in JavaScript?

Patricia Arquette
Release: 2024-12-08 20:31:11
Original
781 people have browsed it

How Can I Efficiently Convert an ArrayBuffer to a Base64 String in JavaScript?

Native Implementation for Converting ArrayBuffer to Base64

Converting an ArrayBuffer to a base64-encoded string is crucial for various use cases, such as multipart POST requests. To efficiently accomplish this, developers often seek native solutions.

SOLUTION

Here's an efficient native function to convert an ArrayBuffer to a base64 string:

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);
}
Copy after login

This function creates a binary string from the ArrayBuffer and uses the native btoa function to generate the base64 string.

ALTERNATIVE APPROACHES

While the above solution is native, non-native implementations may offer better performance. One such implementation can be found here: https://gist.github.com/958841.

PERFORMANCE BENCHMARKS

For a fair comparison, refer to the following performance benchmarks:

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

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template