Base64 Decode to Image Activity is not working?

0
Hello everyone, Within our Native Mobile app, we utilize a custom widget that provides a base64 string representing an image. While attempting to convert this string back to an image within a nanoflow, I encountered an error stating "malformed base64". Interestingly, the same base64 string can be successfully decoded back to an image on websites. Is there something I'm missing or doing incorrectly? Below mentioned is a nanoflow activity available in native file document module.   Code : which that action contained // This file was generated by Mendix Studio Pro. // // WARNING: Only the following code will be retained when actions are regenerated: // - the import list // - the code between BEGIN USER CODE and END USER CODE // - the code between BEGIN EXTRA CODE and END EXTRA CODE // Other code you write will be lost the next time you deploy the project. import "mx-global"; import { Big } from "big.js"; import { Base64 } from 'js-base64';   // BEGIN EXTRA CODE // END EXTRA CODE   /** * @param {string} base64 * @param {MxObject} image * @returns {Promise.<boolean>} */ export async function Base64DecodeToImage(base64, image) { // BEGIN USER CODE if (!base64) { throw new Error("base64 String should not be empty"); } if (!image) { throw new Error("image should not be null"); } const blob = new Blob([Base64.toUint8Array(base64)], { type: "image/png" }); return new Promise((resolve, reject) => { mx.data.saveDocument(image.getGuid(), "camera image", {}, blob, () => resolve(true), reject); }); // END USER CODE }  
asked
1 answers
3

You may try this 

 

async function base64ToImageNative(base64String) {
    // Decode the Base64 string to binary data
    const binaryString = atob(base64String.split(',')[1]);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }

    // Convert Uint8Array
    const file = new Blob([bytes], { type: 'image/png' }); // Adjust the MIME type as necessary

    // Use the Mendix client API
    const mxObject = await mx.data.create({
        entity: "System.FileDocument",
        callback: obj => {
            console.log("Mendix object created", obj);
        },
        error: e => {
            console.error("Error creating Mendix object", e);
        }
    });

    // Set the name and mime type
    mxObject.set("Name", "ImageFileName.png");
    mxObject.set("MimeType", "image/png");

    // Save the file document
    return new Promise((resolve, reject) => {
        mx.data.saveDocument(mxObject.getGuid(), "ImageFileName.png", {}, file, () => {
            console.log("File saved successfully.");
            resolve(mxObject);
        }, (error) => {
            console.error("Error saving file: ", error);
            reject(error);
        });
    });
}

 

answered