Convert byte array to base64 string using Liquid in Dynamics 365/ PowerApps portals

For training and consulting, write to us at info@xrmforyou.com

Liquid and PowerApps portals. I think a match made in heavens. And what can I say about Liquid, a simple yet so powerful template editing language.
And while I was singing praises for Liquid, a colleague came up to me and told that liquid does not have the capability to handle byte arrays and convert them into base64 string.
I was like – Come on! Liquid is powerful.
Quick Reference] Liquid Template - Reference Manual for Dynamics ...
So I decide to have a look into it. Before we go ahead and try for a solution let’s understand when you require to handle byte arrays in dynamics 365 portals. There can be so many scenarios but if you look into specifics when you try to query entityimage in portals you get the result as byte array. The problem is you cannot directly handle byte arrays in liquid directly. But in fact you can do it with a little trick.
What you need to do is to convert your byte content to delimited string. And like other languages, you can do this in Liquid as well.
var stringByteContent = “{{ <your byte array> | join: ‘,’ }}”;
What exactly happens when you do this? You actually convert your individual. So basically your byte array will be represented like this.
image
Okay what’s next, it’s still isn’t base64 string.
Well, the next few steps we will use the everlasting JavaScript which have withstood the test of time. Below is the function which will do the final honours.

function binaryToBase64(content) {
   if (!content) return null;
   var uarr = new Uint8Array(content.split(',').map(function (x) { return parseInt(x); }));
   return btoa(String.fromCharCode.apply(null, uarr));
}

Hope this helps!
Debajit Dutta
(Microsoft MVP)


Discover more from Debajit's Power Apps & Dynamics 365 Blog

Subscribe to get the latest posts sent to your email.

Discover more from Debajit's Power Apps & Dynamics 365 Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading