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.
Contents
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
1 2 3 4 5 |
<?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
<?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
1 2 3 4 5 6 7 8 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 |
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
1 2 3 4 |
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!
Can we allow .mp4 extension in the controller?
Yes, you can modify the code according to your requirement.