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

How to Convert a Base64 String to an ArrayBuffer in JavaScript?

Patricia Arquette
Release: 2024-11-27 14:34:14
Original
1021 people have browsed it

How to Convert a Base64 String to an ArrayBuffer in JavaScript?

Converting Base64 String to ArrayBuffer in JavaScript

Problem:

You want to transform a base64-encoded string into an ArrayBuffer, specifically working with user input from emails that are not available on page load. Your goal is to perform this conversion without external server interaction.

Solution:

To achieve this conversion natively in JavaScript, you can leverage the following steps:

  1. Decode the Base64 String:

    Use the atob() function to decode the base64 string into a binary string.

  2. Create an ArrayBuffer:

    Create a new Uint8Array with a length equal to the binary string's length.

  3. Convert to ArrayBuffer:

    Iterate through each character in the binary string, convert it to a Unicode code point, and store it in the ArrayBuffer.

Example Implementation:

Below is a JavaScript function that performs the base64 to ArrayBuffer conversion:

function base64ToArrayBuffer(base64) {
    var binaryString = atob(base64);
    var bytes = new Uint8Array(binaryString.length);
    for (var i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes.buffer;
}
Copy after login

Usage:

You can use this function to convert a base64-encoded string into an ArrayBuffer:

var base64String = "yourBase64StringHere";
var arrayBuffer = base64ToArrayBuffer(base64String);
Copy after login

Now you have successfully converted the base64 string to an ArrayBuffer, enabling you to work with binary data without external server calls.

The above is the detailed content of How to Convert a Base64 String to an ArrayBuffer 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