{"id":1926,"date":"2021-10-18T12:45:26","date_gmt":"2021-10-18T12:45:26","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/add-image-field-and-preview-image-in-magento-2-admin-ui-component-form\/"},"modified":"2025-05-22T09:54:23","modified_gmt":"2025-05-22T04:24:23","slug":"add-image-field-and-preview-image-in-magento-2-admin-ui-component-form","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/add-image-field-and-preview-image-in-magento-2-admin-ui-component-form\/","title":{"rendered":"How to Add Image Field and Preview Image in Magento 2 Admin UI Component Form"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Images and videos enhance the user experience of any online store. It helps the visitors to interact with your site in a better manner. Also, visual representation is always better than text content so that the information is delivered in an effective manner.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Hence, the Magento 2 store admin may often require to add images in UI component form.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, add customer profile images or document images for verification.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Also, the facility to display the image preview while uploading the images can be helpful to judge the appearance of the image.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">As the default Magento 2 does not offer the option for the same, here\u2019s the solution to&nbsp;add image field and preview image in Magento 2 admin UI component form.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can use the below code to implement image field as shown below:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" src=\"https:\/\/meetanshi.com\/blog\/wp-content\/uploads\/2021\/10\/image-field-and-preview-image-in-Magento-2-Admin-UI-Component-form.png\" alt=\"image field and preview image in Magento Admin UI Component form\" class=\"wp-image-16555\"\/><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">Method to Add Image Field and Preview Image in Magento 2 Admin UI Component Form:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">1. Create&nbsp;<strong>app\/code\/Vendor\/Module\/view\/adminhtml\/ui_component\/product_labels_edit.xml<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"> &lt;field name=\"image\">\n        &lt;argument name=\"data\" xsi:type=\"array\">\n            &lt;item name=\"config\" xsi:type=\"array\">\n                &lt;item name=\"dataType\" xsi:type=\"string\">string&lt;\/item>\n                &lt;item name=\"source\" xsi:type=\"string\">Label    &lt;\/item>\n                &lt;item name=\"label\" xsi:type=\"string\" translate=\"true\">Label Image&lt;\/item>\n                &lt;item name=\"visible\" xsi:type=\"boolean\">true&lt;\/item>\n                &lt;item name=\"formElement\" xsi:type=\"string\">fileUploader&lt;\/item>\n                &lt;item name=\"elementTmpl\" xsi:type=\"string\">ui\/form\/element\/uploader\/uploader&lt;\/item>\n                &lt;item name=\"previewTmpl\" xsi:type=\"string\">Venor_Module\/image-preview&lt;\/item>\n                &lt;item name=\"required\" xsi:type=\"boolean\">false&lt;\/item>\n                &lt;item name=\"sortOrder\" xsi:type=\"number\">4&lt;\/item>\n                &lt;item name=\"uploaderConfig\" xsi:type=\"array\">\n                    &lt;item name=\"url\" xsi:type=\"url\" path=\"router_name\/index\/upload\"\/>\n                &lt;\/item>\n            &lt;\/item>\n        &lt;\/argument>\n&lt;\/field><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">2. Create&nbsp;<strong>app\/code\/Vendor\/Module\/Controller\/Adminhtml\/Index\/Upload.php<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n\nnamespace Vendor\\Module\\Controller\\Adminhtml\\Index;\n\nuse Magento\\Framework\\Controller\\ResultFactory;\nuse Magento\\Backend\\App\\Action\\Context;\nuse Vendor\\Module\\Model\\ImageUploader;\n\nclass Upload extends \\Magento\\Backend\\App\\Action\n{\n    public $imageUploader;\n\n    public function __construct(\n        Context $context,\n        ImageUploader $imageUploader\n    )\n    {\n        parent::__construct($context);\n        $this->imageUploader = $imageUploader;\n    }\n\n    public function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Vendor_Module::label');\n    }\n\n    public function execute()\n    {\n        try {\n            $result = $this->imageUploader->saveFileToTmpDir('image');\n            $result['cookie'] = [\n                'name' => $this->_getSession()->getName(),\n                'value' => $this->_getSession()->getSessionId(),\n                'lifetime' => $this->_getSession()->getCookieLifetime(),\n                'path' => $this->_getSession()->getCookiePath(),\n                'domain' => $this->_getSession()->getCookieDomain(),\n            ];\n        } catch (\\Exception $e) {\n            $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];\n        }\n        return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">3. Create&nbsp;<strong>app\/code\/Vendor\/Module\/Model\/ImageUploader.php<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n\nnamespace Vendor\\Module\\Model;\n\nuse Magento\\MediaStorage\\Helper\\File\\Storage\\Database;\nuse Magento\\Framework\\Filesystem;\nuse Magento\\MediaStorage\\Model\\File\\UploaderFactory;\nuse Magento\\Store\\Model\\StoreManagerInterface;\nuse Psr\\Log\\LoggerInterface;\n\nclass ImageUploader\n{\n    private $coreFileStorageDatabase;\n    private $mediaDirectory;\n    private $uploaderFactory;\n    private $storeManager;\n    private $logger;\n    public $baseTmpPath;\n    public $basePath;    \n    public $allowedExtensions;\n\n    public function __construct(\n        Database $coreFileStorageDatabase,\n        Filesystem $filesystem,\n        UploaderFactory $uploaderFactory,\n        StoreManagerInterface $storeManager,\n        LoggerInterface $logger\n    )\n    {\n        $this->coreFileStorageDatabase = $coreFileStorageDatabase;\n        $this->mediaDirectory = $filesystem->getDirectoryWrite(\\Magento\\Framework\\App\\Filesystem\\DirectoryList::MEDIA);\n        $this->uploaderFactory = $uploaderFactory;\n        $this->storeManager = $storeManager;\n        $this->logger = $logger;\n        $this->baseTmpPath = \"label\/icon\";\n        $this->basePath = \"label\/icon\";\n        $this->allowedExtensions = ['jpg', 'jpeg', 'gif', 'png'];\n    }\n\n    public function setBaseTmpPath($baseTmpPath)\n    {\n        $this->baseTmpPath = $baseTmpPath;\n    }\n\n    public function setBasePath($basePath)\n    {\n        $this->basePath = $basePath;\n    }\n\n    public function setAllowedExtensions($allowedExtensions)\n    {\n        $this->allowedExtensions = $allowedExtensions;\n    }\n\n    public function getBaseTmpPath()\n    {\n        return $this->baseTmpPath;\n    }\n\n    public function getBasePath()\n    {\n        return $this->basePath;\n    }\n\n    public function getAllowedExtensions()\n    {\n        return $this->allowedExtensions;\n    }\n\n    public function getFilePath($path, $imageName)\n    {\n        return rtrim($path, '\/') . '\/' . ltrim($imageName, '\/');\n    }\n\n    public function moveFileFromTmp($imageName)\n    {\n        $baseTmpPath = $this->getBaseTmpPath();\n        $basePath = $this->getBasePath();\n        $baseImagePath = $this->getFilePath($basePath, $imageName);\n        $baseTmpImagePath = $this->getFilePath($baseTmpPath, $imageName);\n        try {\n            $this->coreFileStorageDatabase->copyFile(\n                $baseTmpImagePath,\n                $baseImagePath\n            );\n            $this->mediaDirectory->renameFile(\n                $baseTmpImagePath,\n                $baseImagePath\n            );\n        } catch (\\Exception $e) {\n            throw new \\Magento\\Framework\\Exception\\LocalizedException(\n                __('Something went wrong while saving the file(s).')\n            );\n        }\n        return $imageName;\n    }\n\n    public function saveFileToTmpDir($fileId)\n    {\n        $baseTmpPath = $this->getBaseTmpPath();\n        $uploader = $this->uploaderFactory->create(['fileId' => $fileId]);\n        $uploader->setAllowedExtensions($this->getAllowedExtensions());\n        $uploader->setAllowRenameFiles(true);\n        $result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath));\n        if (!$result) {\n            throw new \\Magento\\Framework\\Exception\\LocalizedException(\n                __('File can not be saved to the destination folder.')\n            );\n        }\n\n        $result['tmp_name'] = str_replace('\\\\', '\/', $result['tmp_name']);\n        $result['path'] = str_replace('\\\\', '\/', $result['path']);\n        $result['url'] = $this->storeManager\n                ->getStore()\n                ->getBaseUrl(\n                    \\Magento\\Framework\\UrlInterface::URL_TYPE_MEDIA\n                ) . $this->getFilePath($baseTmpPath, $result['file']);\n        $result['name'] = $result['file'];\n        if (isset($result['file'])) {\n            try {\n                $relativePath = rtrim($baseTmpPath, '\/') . '\/' . ltrim($result['file'], '\/');\n                $this->coreFileStorageDatabase->saveFile($relativePath);\n            } catch (\\Exception $e) {\n                $this->logger->critical($e);\n                throw new \\Magento\\Framework\\Exception\\LocalizedException(\n                    __('Something went wrong while saving the file(s).')\n                );\n            }\n        }\n        return $result;\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">4. Create&nbsp;<strong>app\/code\/Vendor\/Module\/view\/adminhtml\/web\/template\/image-preview.html<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;div class=\"file-uploader-summary\">\n    &lt;div class=\"file-uploader-preview\">\n        &lt;a attr=\"href: $parent.getFilePreview($file)\" target=\"_blank\">\n            &lt;img\n                class=\"preview-image\"\n                tabindex=\"0\"\n                event=\"load: $parent.onPreviewLoad.bind($parent)\"\n                attr=\"\n                    src: $parent.getFilePreview($file),\n                    alt: $file.name\">\n        &lt;\/a>\n\n        &lt;div class=\"actions\">\n            &lt;button\n                type=\"button\"\n                class=\"action-remove\"\n                data-role=\"delete-button\"\n                attr=\"title: $t('Delete image')\"\n                click=\"$parent.removeFile.bind($parent, $file)\">\n                &lt;span translate=\"'Delete image'\"\/>\n            &lt;\/button>\n        &lt;\/div>\n    &lt;\/div>\n\n    &lt;div class=\"file-uploader-filename\" text=\"$file.name\"\/>\n    &lt;div class=\"file-uploader-meta\">\n        &lt;text args=\"$file.previewWidth\"\/>x&lt;text args=\"$file.previewHeight\"\/>\n    &lt;\/div>\n&lt;\/div><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">5. Create&nbsp;<strong>app\/code\/Vendor\/Module\/etc\/di.xml<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;type name=\"Vendor\\Module\\Model\\ImageUploader\">\n    &lt;arguments>\n        &lt;argument name=\"baseTmpPath\" xsi:type=\"string\">label\/tmp\/image&lt;\/argument>\n        &lt;argument name=\"basePath\" xsi:type=\"string\">label\/image&lt;\/argument>\n        &lt;argument name=\"allowedExtensions\" xsi:type=\"array\">\n            &lt;item name=\"jpg\" xsi:type=\"string\">jpg&lt;\/item>\n            &lt;item name=\"jpeg\" xsi:type=\"string\">jpeg&lt;\/item>\n            &lt;item name=\"gif\" xsi:type=\"string\">gif&lt;\/item>\n            &lt;item name=\"png\" xsi:type=\"string\">png&lt;\/item>\n        &lt;\/argument>\n    &lt;\/arguments>\n&lt;\/type><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">That\u2019s it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Also, do share the solution with the Magento Community via social media.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Thank you.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Images and videos enhance the user experience of any online store. It helps the visitors to interact with your site in a better manner. Also,&#8230;<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[34],"tags":[],"class_list":["post-1926","post","type-post","status-publish","format-standard","hentry","category-magento"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1926","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=1926"}],"version-history":[{"count":6,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1926\/revisions"}],"predecessor-version":[{"id":17762,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1926\/revisions\/17762"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=1926"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=1926"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=1926"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}