How To

Magento 2: Allow Custom Image Type When Uploading Image from Page Builder

Hello Magento Friends,

Today I will explain How to Allow Custom Image Type When Uploading Image from Page Builder in Magento 2.

The page builder in Magento 2 is a drag-and-drop tool for creating content. With Page Builder, you can work with various content types to build a page. One such content type in Magento 2 Page Builder is images. Apart from page builder, you can add image to product programmatically in Magento 2. Check out the article for Magento 2 add image to product programmatically.

One can add a custom image uploader in Magento 2 page builder. Whenever there is a need to add custom image in Magento 2, you need to add custom image uploader. For example, if you want to add WebP images in Magento 2, you can allow custom option image for Magento 2. By using Magento 2 WebP Image Converter automatically converts your images to WebP format.

Let’s get started with the Steps to Allow Custom Image Type When Uploading Image from Page Builder in Magento 2.

Steps to Allow Custom Image Type When Uploading Image from Page Builder in Magento 2:

Step 1: Move to the below file path

app\code\Vendor\Extension\etc\di.xml

And code as follows

<?xml version="1.0" encoding="UTF-8"?> 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <preference for="Magento\PageBuilder\Controller\Adminhtml\ContentType\Image\Upload" 
    type="Vendor\Extension\Controller\Adminhtml\ContentType\Image\Upload" />
</config>

Step 2: Now move to the below file path

app\code\Vendor\Extension\Controller\Adminhtml\ContentType\Image\Upload.php

Add the below-mentioned code

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */namespace Vendor\Extension\Controller\Adminhtml\ContentType\Image;

use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Filesystem;

class Upload extends \Magento\Backend\App\Action implements HttpPostActionInterface
{
    const UPLOAD_DIR = 'wysiwyg';

    const ADMIN_RESOURCE = 'Magento_Backend::content';

    private $directoryList;
    private $resultJsonFactory;
    private $uploaderFactory;
    private $storeManager;
    private $cmsWysiwygImages;
    private $mediaDirectory;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\File\UploaderFactory $uploaderFactory,
        \Magento\Framework\Filesystem\DirectoryList $directoryList,
        \Magento\Cms\Helper\Wysiwyg\Images $cmsWysiwygImages,
        Filesystem $filesystem = null)
    {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->storeManager = $storeManager;
        $this->uploaderFactory = $uploaderFactory;
        $this->directoryList = $directoryList;
        $this->cmsWysiwygImages = $cmsWysiwygImages;
        $filesystem = $filesystem ?? ObjectManager::getInstance()->create(Filesystem::class);
        $this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
        parent::__construct($context);
    }

    private function getFilePath($path, $imageName)
    {
        return rtrim($path, '/') . '/' . ltrim($imageName, '/');
    }
   
    public function execute()
    {
        $fieldName = $this->getRequest()->getParam('param_name');
        $fileUploader = $this->uploaderFactory->create(['fileId' => $fieldName]);

        // Set our parameters
        $fileUploader->setFilesDispersion(false);
        $fileUploader->setAllowRenameFiles(true);
        $fileUploader->setAllowedExtensions(['jpeg','jpg','png','gif','customtype']);
        $fileUploader->setAllowCreateFolders(true);

        try
        {
            if (!$fileUploader->checkMimeType(['image/png', 'image/jpeg', 'image/gif', 'image/customtype']))
            {
                throw new \Magento\Framework\Exception\LocalizedException(__('File validation failed.'));
            }

            $result = $fileUploader->save($this->getUploadDir());
            $baseUrl = $this->_backendUrl->getBaseUrl(['_type' => \Magento\Framework\UrlInterface::URL_TYPE_MEDIA]);
            $result['id'] = $this->cmsWysiwygImages->idEncode($result['file']);
            $result['url'] = $baseUrl . $this->getFilePath(self::UPLOAD_DIR, $result['file']);
        }
        catch (\Exception $e)
        {
            $result = [
                'error' => $e->getMessage(),
                'errorcode' => $e->getCode()
            ];
        }
        return $this->resultJsonFactory->create()->setData($result);
    }

    private function getUploadDir()
    {
        return $this->mediaDirectory->getAbsolutePath(self::UPLOAD_DIR);
    }
}

Step 3: Now move to the following file path

app\code\Vendor\Extension\view\base\requirejs-config.js

Then add the code as below

var config = {
    map: {
        '*': {
            'Magento_Ui/js/form/element/file-uploader':
                'Vendor_Extension/js/form/element/file-uploader'
        }
    }
};

Step 4: Then navigate to the below file path

app\code\Vendor\Extension\view\base\web\js\form\element\file-uploader.js

Add code as follows

define([
    'mage/url',
    'jquery',
    'underscore',
    'mageUtils',
    'Magento_Ui/js/modal/alert',
    'Magento_Ui/js/lib/validation/validator',
    'Magento_Ui/js/form/element/abstract',
    'mage/backend/notification',
    'mage/translate',
    'jquery/file-uploader',
    'mage/adminhtml/tools',
    
], function (urlBuilder, $, _, utils, uiAlert, validator, Element, notification, $t) {
    'use strict';
    return Element.extend({
        defaults: {
            value: [],
            aggregatedErrors: [],
            maxFileSize: false,
            isMultipleFiles: false,
            placeholderType: 'document', // 'image', 'video'
            allowedExtensions: false,
            previewTmpl: 'ui/form/element/uploader/preview',
            dropZone: '[data-role=drop-zone]',
            isLoading: false,
            uploaderConfig: {
                dataType: 'json',
                sequentialUploads: true,
                formData: {
                    'form_key': window.FORM_KEY
                }
            },
            tracks: {
                isLoading: true
            }
        },
        /**
         * Initializes file uploader plugin on provided input element.
         *
         * @param {HTMLInputElement} fileInput
         * @returns {FileUploader} Chainable.
         */        initUploader: function (fileInput) {
            this.$fileInput = fileInput;
            _.extend(this.uploaderConfig, {
                dropZone: $(fileInput).closest(this.dropZone),
                change: this.onFilesChoosed.bind(this),
                drop: this.onFilesChoosed.bind(this),
                add: this.onBeforeFileUpload.bind(this),
                fail: this.onFail.bind(this),
                done: this.onFileUploaded.bind(this),
                start: this.onLoadingStart.bind(this),
                stop: this.onLoadingStop.bind(this)
            });
            $(fileInput).fileupload(this.uploaderConfig);
            return this;
        },
        /**
         * Defines initial value of the instance.
         *
         * @returns {FileUploader} Chainable.
         */        setInitialValue: function () {
            var value = this.getInitialValue();

            value = value.map(this.processFile, this);
            this.initialValue = value.slice();
            this.value(value);
            this.on('value', this.onUpdate.bind(this));
            this.isUseDefault(this.disabled());
            return this;
        },
        /**
         * Empties files list.
         *
         * @returns {FileUploader} Chainable.
         */        clear: function () {
            this.value.removeAll();
            return this;
        },
        /**
         * Checks if files list contains any items.
         *
         * @returns {Boolean}
         */        hasData: function () {
            return !!this.value().length;
        },

        /**
         * Resets files list to its' initial value.
         *
         * @returns {FileUploader}
         */        reset: function () {
            var value = this.initialValue.slice();

            this.value(value);
            return this;
        },
        /**
         * Adds provided file to the files list.
         *
         * @param {Object} file
         * @returns {FileUploader} Chainable.
         */        addFile: function (file) {
            file = this.processFile(file);
            this.isMultipleFiles ?
                this.value.push(file) :
                this.value([file]);
            return this;
        },
        /**
         * Retrieves from the list file which matches
         * search criteria implemented in itertor function.
         *
         * @param {Function} fn - Function that will be invoked
         *      for each file in the list.
         * @returns {Object}
         */        getFile: function (fn) {
            return _.find(this.value(), fn);
        },
        /**
         * Removes provided file from thes files list.
         *
         * @param {Object} file
         * @returns {FileUploader} Chainable.
         */        removeFile: function (file) {
            this.value.remove(file);
            return this;
        },
        /**
         * May perform modifications on the provided
         * file object before adding it to the files list.
         *
         * @param {Object} file
         * @returns {Object} Modified file object.
         */        processFile: function (file) {
            file.previewType = this.getFilePreviewType(file);
            if (!file.id && file.name) {
                file.id = Base64.mageEncode(file.name);
            }
            this.observe.call(file, true, [
                'previewWidth',
                'previewHeight'
            ]);
            return file;
        },
        /**
         * Formats incoming bytes value to a readable format.
         *
         * @param {Number} bytes
         * @returns {String}
         */        formatSize: function (bytes) {
            var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'],
                i;
            if (bytes === 0) {
                return '0 Byte';
            }
            i = window.parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
            return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
        },
        /**
         * Returns path to the files' preview image.
         *
         * @param {Object} file
         * @returns {String}
         */        getFilePreview: function (file) {
            return file.url;
        },
        /**
         * Returns path to the file's preview template.
         *
         * @returns {String}
         */        getPreviewTmpl: function () {
            return this.previewTmpl;
        },
        /**
         * Checks if provided file is allowed to be uploaded.
         *
         * @param {Object} file
         * @returns {Object} Validation result.
         */        isFileAllowed: function (file) {
            var result;
           _.every([
                this.isExtensionAllowed(file),
                this.isSizeExceeded(file)
            ], function (value) {
                result = value;
                return value.passed;
            });
            return result;
        },
        /**
         * Checks if extension of provided file is allowed.
         *
         * @param {Object} file - File to be checked.
         * @returns {Boolean}
         */        isExtensionAllowed: function (file) {
            this.allowedExtensions = this.allowedExtensions + ' webp';
            return validator('validate-file-type', file.name, this.allowedExtensions);
        },
        /**
         * Get simplified file type.
         *
         * @param {Object} file - File to be checked.
         * @returns {String}
         */        getFilePreviewType: function (file) {
            var type;
            if (!file.type) {
                return 'document';
            }
            type = file.type.split('/')[0];
            return type !== 'image' && type !== 'video' ? 'document' : type;
        },
        /**
         * Checks if size of provided file exceeds
         * defined in configuration size limits.
         *
         * @param {Object} file - File to be checked.
         * @returns {Boolean}
         */        isSizeExceeded: function (file) {
            return validator('validate-max-size', file.size, this.maxFileSize);
        },
        /**
         * Displays provided error message.
         *
         * @param {String} msg
         * @returns {FileUploader} Chainable.
         */        notifyError: function (msg) {
            var data = {
                content: msg
            };
            if (this.isMultipleFiles) {
                data.modalClass = '_image-box';
            }
            uiAlert(data);
            return this;
        },
        /**
         * Performs data type conversions.
         *
         * @param {*} value
         * @returns {Array}
         */        normalizeData: function (value) {
            return utils.isEmpty(value) ? [] : value;
        },
        /**
         * Checks if files list is different
         * from its' initial value.
         *
         * @returns {Boolean}
         */        hasChanged: function () {
            var value = this.value(),
                initial = this.initialValue;
            return !utils.equalArrays(value, initial);
        },
        /**
         * Handler which is invoked when files are choosed for upload.
         * May be used for implementation of additional validation rules,
         * e.g. total files and a total size rules.
         *
         * @param {Event} event - Event object.
         * @param {Object} data - File data that will be uploaded.
         */        onFilesChoosed: function (event, data) {
            // no option exists in file uploader for restricting upload chains to single files
            // this enforces that policy
            if (!this.isMultipleFiles) {
                data.files.splice(1);
            }
        },
        /**
         * Handler which is invoked prior to the start of a file upload.
         *
         * @param {Event} event - Event object.
         * @param {Object} data - File data that will be uploaded.
         */        onBeforeFileUpload: function (event, data) {
            var file = data.files[0],
                allowed = this.isFileAllowed(file),
                target = $(event.target);
            if (this.disabled()) {
                this.notifyError($t('The file upload field is disabled.'));
                return;
            }
            if (allowed.passed) {
                target.on('fileuploadsend', function (eventBound, postData) {
                    postData.data.append('param_name', this.paramName);
                }.bind(data));
                target.fileupload('process', data).done(function () {
                    data.submit();
                });
            } else {
                this.aggregateError(file.name, allowed.message);
                // if all files in upload chain are invalid, stop callback is never called; this resolves promise
                if (this.aggregatedErrors.length === data.originalFiles.length) {
                    this.uploaderConfig.stop();
                }
            }
        },
        /**
         * Add error message associated with filename for display when upload chain is complete
         *
         * @param {String} filename
         * @param {String} message
         */        aggregateError: function (filename, message) {
            this.aggregatedErrors.push({
                filename: filename,
                message: message
            });
        },
        /**
         * @param {Event} event
         * @param {Object} data
         */        onFail: function (event, data) {
            console.error(data.jqXHR.responseText);
            console.error(data.jqXHR.status);
        },
        /**
         * Handler of the file upload complete event.
         *
         * @param {Event} event
         * @param {Object} data
         */        onFileUploaded: function (event, data) {
            var uploadedFilename = data.files[0].name,
                file = data.result,
                error = file.error;
            error ?
                this.aggregateError(uploadedFilename, error) :
                this.addFile(file);
        },
        /**
         * Load start event handler.
         */        onLoadingStart: function () {
            this.isLoading = true;
        },
        /**
         * Load stop event handler.
         */        onLoadingStop: function () {
            var aggregatedErrorMessages = [];

            this.isLoading = false;
            if (!this.aggregatedErrors.length) {
                return;
            }
            if (!this.isMultipleFiles) { // only single file upload occurred; use first file's error message
                aggregatedErrorMessages.push(this.aggregatedErrors[0].message);
            } else { // construct message from all aggregatedErrors
                _.each(this.aggregatedErrors, function (error) {
                    notification().add({
                        error: true,
                        message: '%s' + error.message, // %s to be used as placeholder for html injection

                        /**
                         * Adds constructed error notification to aggregatedErrorMessages
                         *
                         * @param {String} constructedMessage
                         */                        insertMethod: function (constructedMessage) {
                            var escapedFileName = $('<div>').text(error.filename).html(),
                                errorMsgBodyHtml = '<strong>%s</strong> %s.<br>'
                                    .replace('%s', escapedFileName)
                                    .replace('%s', $t('was not uploaded'));

                            // html is escaped in message body for notification widget; prepend unescaped html here
                            constructedMessage = constructedMessage.replace('%s', errorMsgBodyHtml);
                            aggregatedErrorMessages.push(constructedMessage);
                        }
                    });
                });
            }
            this.notifyError(aggregatedErrorMessages.join(''));
            // clear out aggregatedErrors array for this completed upload chain
            this.aggregatedErrors = [];
        },
        /**
         * Handler function which is supposed to be invoked when
         * file input element has been rendered.
         *
         * @param {HTMLInputElement} fileInput
         */        onElementRender: function (fileInput) {
            this.initUploader(fileInput);
        },
        /**
         * Handler of the preview image load event.
         *
         * @param {Object} file - File associated with an image.
         * @param {Event} event
         */        onPreviewLoad: function (file, event) {
            var img = event.currentTarget;
            file.previewWidth = img.naturalWidth;
            file.previewHeight = img.naturalHeight;
        },
        /**
         * Restore value to default
         */        restoreToDefault: function () {
            var defaultValue = utils.copy(this.default);
            defaultValue.map(this.processFile, this);
            this.value(defaultValue);
        },
        /**
         * Update whether value differs from default value
         */        setDifferedFromDefault: function () {
            var value = utils.copy(this.value());
            this.isDifferedFromDefault(!_.isEqual(value, this.default));
        }
    });
});

Step 5: After that run the below commands

sudo php bin/magento setup:upgrade
sudo php bin/magento setup:di:compile
sudo php bin/magento setup:static-content:deploy -f
sudo php bin/magento cache:flush

Conclusion:

This way you can easily allow custom image type when uploading image from page builder in Magento 2. If you have any doubt about executing the above steps, feel free to ask me through the comment part. Share the tutorial with your friends and stay in touch with us.

Happy Coding!

Click to rate this post!
[Total: 8 Average: 3.5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

View Comments

Recent Posts

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

6 days ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago

Top 10 Tips to Hire Shopify Developers

As the world of eCommerce continues to thrive, Shopify has become one of the most…

2 weeks ago

Managing Browser Events and Navigation in Shopify Remix: useBeforeUnload, useHref, and useLocation Hooks

Shopify Remix is an innovative framework that provides a streamlined experience for building fast, dynamic,…

2 weeks ago

Ultimate Guide to Hiring a Top Shopify Development Agency

Building a successful eCommerce store requires expertise, and for many businesses, Shopify has become the…

2 weeks ago