- August 30, 2019
- Posted by: iSummation Team
- Category: Development

In this era, Software as a service (SaaS) becomes more and more popular, and I am working on one of SaaS product for USA based investigative company using MEAN Stack development approach, and there was a requirement where we want to integrate 3rd party feature into the project using their JavaScript.
There is one export feature provided by them to export report and we want to save that report at our end. So, on call-back of their export feature, they return data as buffer value and we want to write a new file using that buffer value.
Here first we need to convert received arrayBuffer value into Base64 encoded string and then we write a file using toBinary() function of CFML by passing Base64 encoded string in it. So, I have utilized the below custom JavaScript function arrayBufferToBase64() to accomplish the requirement.
1 2 3 4 5 6 7 8 9 |
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 ); } |
Here, The Uint8Array typed array represents an array of 8-bit unsigned integers.
The fromCharCode() method converts Unicode values into characters. It is a static method of the String object.
The btoa() method encodes a string in base-64.
1 2 3 4 5 6 7 8 9 |
function base64ToArrayBuffer(base64) { var binary_string = window.atob(base64); var len = binary_string.length; var bytes = new Uint8Array( len ); for (var i = 0; i < len; i++) { bytes[i] = binary_string.charCodeAt(i); } return bytes.buffer; } |
The atob() method used to decode a base-64 encoded string.
The charCodeAt() method returns the Unicode of the character at the specified index in a string.
Hope this helps you.