avatar
Upload images and files to the Digital Assets Manager (DAM) AEM

> With adding custom clientlib script files to specific AEM component, we can totally handle uploading image from out of AEM to DAM folder. Let us follow step by step as below:

components
|- content
|  |- image
|  |  |- clientlib-author-dialog [cq:ClientLibraryFolder]
|  |  |  |- js
|  |  |  |  |- js.txt
|  |  |  |  |- js 
|  |  |  |  |  |- mycustom.js

Note: We need cq.authoring.dialog.all in categories because image is inherited from AEM component. You can refer link here.

> We will setup mycustom.js as below. TO DO where you handle logic uploading image using ajax.

(function(document, $) {
    "use strict";

    const DIALOG_RESOURCE_TYPE = "flagtick/components/content/image";

    function isTargetDialog($formElement, dlgResourceType) {
        const resourceType = $formElement.find("input[name='./sling:resourceType']").val();
        return resourceType === dlgResourceType;
    }

    $(document).on("dialog-ready", function () {
        const $formElement = $(this).find('coral-dialog form.foundation-form');
        if (!isTargetDialog($formElement, DIALOG_RESOURCE_TYPE)) {
            console.debug("Ignore the listener, not a ", DIALOG_RESOURCE_TYPE, " dialog.");
            return;
        } else {
            /** TODO */
        }
    });

})(document, Granite.$);

> We do manipulations on Image component by click browse to upload image from local machine.

Note: Inspect Element to be aware changes on image element.

> In HTML img src Attribute, we have string as base64 image data. Here is link generated and open in browser: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA... We get image path and image name from Image element. After that, perform with ajax to call servlet.

(function(document, $) {
    "use strict";

    const DIALOG_RESOURCE_TYPE = "flagtick/components/content/image";

    function isTargetDialog($formElement, dlgResourceType) {
        const resourceType = $formElement.find("input[name='./sling:resourceType']").val();
        return resourceType === dlgResourceType;
    }

    function performAjaxFunc(data) {
        $.ajax({
            type: 'POST',
            url: '/bin/flagtick/upload',
            data: data,
            success: function(message) {
                console.log(message);
            },
            error: function(error) {
                console.log(error);
            }
        });
    }

    $(document).on("dialog-ready", function () {
        const $formElement = $(this).find('coral-dialog form.foundation-form');
        if (!isTargetDialog($formElement, DIALOG_RESOURCE_TYPE)) {
            console.debug("Ignore the listener, not a ", DIALOG_RESOURCE_TYPE, " dialog.");
            return;
        } else {
            $(document).on("click", ".cq-dialog-submit", function() {
                let el = $(".cq-FileUpload-thumbnail-img img");
                let path = el.attr("src").split('image')[0];
                let title = el.attr("title");
                let data = 'path=' + path + '&title=' + title;

                performAjaxFunc(data);
            });
        }
    });
})(document, Granite.$);

> Follow up the link to create custom servlet in AEM. Here is an example for /bin/flagtick/upload.

package com.flagtick.core.servlets;


import com.day.cq.dam.api.AssetManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.servlet.Servlet;
import java.io.IOException;

@Component(service = Servlet.class, property = {
        Constants.SERVICE_DESCRIPTION + "= HTTP servlet",
        "sling.servlet.methods=" + HttpConstants.METHOD_POST,
        "sling.servlet.paths=" + "/bin/flagtick/upload" }
)
public class FlagtickCustomServlet extends SlingAllMethodsServlet {

    private static final long serialVersionUID = -2014397651676211439L;
    private static final Logger log = LoggerFactory.getLogger(FlagtickCustomServlet.class);
    private static final String ROOT_PATH = "/content/dam/flagtick/myfolder/";

    @Override
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {
        try {
            String path = StringUtils.EMPTY;
            String title = StringUtils.EMPTY;
            if (!StringUtils.isBlank(request.getParameter("path"))) {
                path = request.getParameter("path").replace("_jcr_content", "jcr:content") + "/image/file";
            }
            if (!StringUtils.isBlank(request.getParameter("title"))) {
                title = request.getParameter("title");
            }

            Node imgNode = request.getResourceResolver().getResource(path).adaptTo(Node.class);
            Binary binary;
            try {
                binary = imgNode.getNode("jcr:content").getProperty("jcr:data").getBinary();
                synchFileToDAM(binary, title, request.getResource().getResourceResolver());
            } catch (RepositoryException e) {
                throw new RuntimeException(e);
            }


            response.getWriter().println(title);
        } catch (IOException e) {
            log.error(e.getCause().getMessage());
        }
    }

    private void synchFileToDAM(Binary binary, String imgName, ResourceResolver resourceResolver) {
        try {
            // Use AssetManager to place the file into the AEM DAM
            AssetManager assetMgr = resourceResolver.adaptTo(AssetManager.class);
            String path = ROOT_PATH + imgName;
            assetMgr.createOrUpdateAsset(path, binary,"image/jpeg", true);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}

> Go to Asset folder in AEM and observe result as below:

24
add clientlibs in AEM component include client libraries in AEM component
You need to login to do this manipulation!