Home >Web Front-end >JS Tutorial >How to Convert a Base64 String to an 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:
Decode the Base64 String:
Use the atob() function to decode the base64 string into a binary string.
Create an ArrayBuffer:
Create a new Uint8Array with a length equal to the binary string's length.
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; }
Usage:
You can use this function to convert a base64-encoded string into an ArrayBuffer:
var base64String = "yourBase64StringHere"; var arrayBuffer = base64ToArrayBuffer(base64String);
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!