AEM 6540 - Show File size in units in Assets Metadata Editor

Goal


Adding file size (./jcr:content/metadata/dam:size) field in metadata editor shows the size in bytes. The simple logic in this extension is for showing size in other units (KB, MB, GB etc.)

Thank you internet for the conversion code snippet

Package Install | Github


Product



Extension



Solution


1) Login to CRXDE Lite (http://localhost:4502/crx/de), create folder /apps/eaem-assets-metadata-file-size-units

2) Create node /apps/eaem-assets-metadata-file-size-units/clientlib of type cq:ClientLibraryFolder, add String[] property categories with value [dam.gui.coral.metadataeditor], String[] property dependencies with value lodash.

3) Create file (nt:file) /apps/eaem-assets-metadata-file-size-units/clientlib/js.txt, add

                        file-size-units.js

4) Create file (nt:file) /apps/eaem-assets-metadata-file-size-units/clientlib/file-size-units.js, add the following code

(function($, $document) {
    var FILE_SIZE_NAME = "./jcr:content/metadata/dam:size",
        initialized = false;

    $document.on("foundation-contentloaded", init);

    function init(){
        if(initialized){
            return;
        }

        initialized = true;

        convertFileSize();
    }

    function convertFileSize(){
        var $damSize = $("[name='" + FILE_SIZE_NAME + "']");

        if(_.isEmpty($damSize)){
            return;
        }

        var sizeInBytes = $damSize.val();

        $damSize.val(!sizeInBytes ?  "Unavailable" : formatBytes(parseInt(sizeInBytes), 2));
    }

    function formatBytes(bytes, decimals) {
        if (bytes === 0){
            return '0 Bytes';
        }

        const k = 1024;
        const dm = decimals < 0 ? 0 : decimals;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));

        return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
    }
}(jQuery, jQuery(document)));

No comments:

Post a Comment