Home  >  Article  >  Web Front-end  >  How to Decode Base64 Strings to ArrayBuffers in JavaScript?

How to Decode Base64 Strings to ArrayBuffers in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-17 20:06:02675browse

How to Decode Base64 Strings to ArrayBuffers in JavaScript?

Decoding Base64 Strings to ArrayBuffer in JavaScript

In JavaScript, converting a Base64 string to an ArrayBuffer can be accomplished without using external server requests. This process enables the processing of user-provided Base64 data within the browser itself.

To achieve this conversion, the following steps can be taken:

function base64ToArrayBuffer(base64) {
    const binaryString = atob(base64); // Convert Base64 to raw binary string
    const bytes = new Uint8Array(binaryString.length); // Create new Uint8Array
    for (let i = 0; i < binaryString.length; i++) { // Loop through each char in binary string
        bytes[i] = binaryString.charCodeAt(i); // Set byte at index to corresponding code
    }
    return bytes.buffer; // Return converted ArrayBuffer
}

This function begins by decoding the Base64 string using the native atob() function, which transforms it into a raw binary string. It then creates a new Uint8Array with the same length as the binary string and iterates over each character in the binary string. For each character, its corresponding code point is extracted and assigned to the appropriate Byte in the Uint8Array. Finally, the Uint8Array's buffer property, which represents the actual ArrayBuffer, is returned as the result.

To demonstrate its usage:

const base64String = "JVBERi0xLjQK";
const arrayBuffer = base64ToArrayBuffer(base64String);

In this example, the base64String is converted from Base64 encoding to an arrayBuffer using the base64ToArrayBuffer() function. This ArrayBuffer can then be further processed as needed within JavaScript.

The above is the detailed content of How to Decode Base64 Strings to ArrayBuffers in JavaScript?. 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