Home > Web Front-end > JS Tutorial > How to Convert Base64 Strings to ArrayBuffers in Native JavaScript?

How to Convert Base64 Strings to ArrayBuffers in Native JavaScript?

Mary-Kate Olsen
Release: 2024-11-24 03:47:21
Original
527 people have browsed it

How to Convert Base64 Strings to ArrayBuffers in Native JavaScript?

Converting Base64 Strings to ArrayBuffers with Native JavaScript

In various scenarios, such as working with data from emails or other user-provided sources, it becomes necessary to convert a base64-encoded string into an ArrayBuffer. JavaScript offers a straightforward means to accomplish this conversion without the need for external server communication.

Native Conversion Method Using atob and Uint8Array

The following function effectively converts a base64 string to an ArrayBuffer:

function base64ToArrayBuffer(base64) {
    // Decode the base64 string into a binary string
    var binaryString = atob(base64);

    // Create a new Uint8Array with the length of the binary string
    var bytes = new Uint8Array(binaryString.length);

    // Iterate through each character of the binary string and convert it to a byte
    for (var i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }

    // Return the ArrayBuffer containing the converted bytes
    return bytes.buffer;
}
Copy after login

In this function:

  • The atob() method decodes the base64 string into a binary string.
  • A Uint8Array is created to hold the binary data.
  • Each character in the binary string is converted to its corresponding byte using charCodeAt().
  • The buffer property of the Uint8Array returns the ArrayBuffer.

By utilizing this native conversion method, you can easily transform base64-encoded user input into ArrayBuffers for further processing.

The above is the detailed content of How to Convert Base64 Strings to ArrayBuffers in Native 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