How to see the content of an Image in a Javascript Action and to convert it to base64 format?

0
Hi, I would like to create a custom JavaScript Action to convert a Binary Image Content to Base64 format. In the model I created an entity MyImage that extends the System.Image adding property Base64Content of type string. I created the following javascript code just to print the properties of the image in input: // 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 { Big } from "big.js"; // BEGIN EXTRA CODE // END EXTRA CODE /** * @param {MxObject} img * @returns {Promise.<string>} */ export async function ConvertImageToBase64(img) { // BEGIN USER CODE debugger; mx.data.get({ guid: img._guid, callback: function(mxobj) { var attrs = mxobj.getAttributes(); for(var i=0;i<attrs.length;i++) { var value = mxobj.get(attrs[i]); console.log(attrs[i]+": " + value); } } }); // END USER CODE } I created the following page to browse an image and Save it. I can see the image in the image viewer and after I click on the button “Convert Image to Base 64” to call the javascript action. In the console of the browser, I can see that the property Name is filled, Size > 0, HasContents is true but the property Contents is empty so I cannot use it to convert to base 64. What’s wrong? How could I get the content of the image and convert it to base 64? Thanks.
asked
1 answers
0

Hi Marco

I hope this help you out. Please not this code is untested and will probably not work on Native platform

Cheers, Andries

function toDataUrl(url) {
    return new Promise(resolve => {
        const xhr = new XMLHttpRequest();
        xhr.onload = () => {
            const reader = new FileReader();
            reader.onloadend = () => {
                resolve(reader.result);
            };
            reader.readAsDataURL(xhr.response);
        };
        xhr.open("GET", url);
        xhr.responseType = "blob";
        xhr.send();
    });
}
// END EXTRA CODE
/**
 * @param {MxObject} imageDocument
 * @returns {Promise.<string>}
 */
export async function ImageToBase64String(imageDocument) {
    // BEGIN USER CODE
    // TODO make it Native, implement error cases
    const url = mx.data.getDocumentUrl(imageDocument.getGuid(), imageDocument.get("changeDate"));
    return toDataUrl(url);
    // END USER CODE
}

 

answered