cancel
Showing results for 
Search instead for 
Did you mean: 

[SAP MDK] Converting Binary to Base64 for Android/iOS

Khaled_Elghali
SAP Champion
SAP Champion
206

Hello MDK Community,

I am currently developing an application using MDK & Mobile Services, which needs to send a photo (from the attachment) to the SAP backend via REST upon pressing a button.
I have developed the following MDK rule (getImageString.js) to perform the conversion from the image obj to base64:

 

export default function getImageString(clientAPI) {
    var attachmControl = clientAPI.getPageProxy().getControl('SectionedTable0').getControl('AttachPhoto');
    var arrayBuffer = attachmControl.getValue()[0].content;
    return arrayBufferToBase64(arrayBuffer);
}

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 is the problem!
}

 

Problem:

This script works fine in the browser (WebApp), but it fails on mobile devices (tested on an Android device) at the point of converting binary to base64 due to the use of the window, which is likely not recognized on mobile devices. The issue specifically occurs at the line:

 

return window.btoa(binary);

 

Question:

Is there an alternative method to convert binary to base64 that works on mobile devices (Android/iOS) or a method from the clientAPI interface that can be used for this conversion?
I am open to alternative solutions to achieve this functionality.

For reference, I'm using SAP Mobile Services for the backend orchestration and the latest MDK client version.
Thank you in advance for your assistance!
Best regards, Khaled

PS: For simplicity, this example assumes only one attachment.

View Entire Topic
mingkho
Product and Topic Expert
Product and Topic Expert
0 Kudos

Hello Khaled

Good news, MDK 24.11.0 which was just released last week introduced this new API:

binaryToBase64String on the ClientAPI class

Here's an example using your initial sample code as base.

export default async function getImageString(clientAPI) {
    var attachmControl = clientAPI.getPageProxy().getControl('SectionedTable0').getControl('AttachPhoto');
    var arrayBuffer = attachmControl.getValue()[0].content;
    var base64str = await clientAPI.binaryToBase64String(arrayBuffer);
    return base64str;
}