How to Add Image Field and Preview Image in Magento 2 Admin UI Component Form
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.
Hence, the Magento 2 store admin may often require to add images in UI component form.
For example, add customer profile images or document images for verification.
Also, the facility to display the image preview while uploading the images can be helpful to judge the appearance of the image.
As the default Magento 2 does not offer the option for the same, here’s the solution to add image field and preview image in Magento 2 admin UI component form.
You can use the below code to implement image field as shown below:
Method to Add Image Field and Preview Image in Magento 2 Admin UI Component Form:
- Create app/code/Vendor/Module/view/adminhtml/ui_component/product_labels_edit.xml
123456789101112131415161718<field name="image"><argument name="data" xsi:type="array"><item name="config" xsi:type="array"><item name="dataType" xsi:type="string">string</item><item name="source" xsi:type="string">Label </item><item name="label" xsi:type="string" translate="true">Label Image</item><item name="visible" xsi:type="boolean">true</item><item name="formElement" xsi:type="string">fileUploader</item><item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item><item name="previewTmpl" xsi:type="string">Venor_Module/image-preview</item><item name="required" xsi:type="boolean">false</item><item name="sortOrder" xsi:type="number">4</item><item name="uploaderConfig" xsi:type="array"><item name="url" xsi:type="url" path="router_name/index/upload"/></item></item></argument></field> - Create app/code/Vendor/Module/Controller/Adminhtml/Index/Upload.php
12345678910111213141516171819202122232425262728293031323334353637383940414243<?phpnamespace Vendor\Module\Controller\Adminhtml\Index;use Magento\Framework\Controller\ResultFactory;use Magento\Backend\App\Action\Context;use Vendor\Module\Model\ImageUploader;class Upload extends \Magento\Backend\App\Action{public $imageUploader;public function __construct(Context $context,ImageUploader $imageUploader){parent::__construct($context);$this->imageUploader = $imageUploader;}public function _isAllowed(){return $this->_authorization->isAllowed('Vendor_Module::label');}public function execute(){try {$result = $this->imageUploader->saveFileToTmpDir('image');$result['cookie'] = ['name' => $this->_getSession()->getName(),'value' => $this->_getSession()->getSessionId(),'lifetime' => $this->_getSession()->getCookieLifetime(),'path' => $this->_getSession()->getCookiePath(),'domain' => $this->_getSession()->getCookieDomain(),];} catch (\Exception $e) {$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];}return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);}} - Create app/code/Vendor/Module/Model/ImageUploader.php
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132<?phpnamespace Vendor\Module\Model;use Magento\MediaStorage\Helper\File\Storage\Database;use Magento\Framework\Filesystem;use Magento\MediaStorage\Model\File\UploaderFactory;use Magento\Store\Model\StoreManagerInterface;use Psr\Log\LoggerInterface;class ImageUploader{private $coreFileStorageDatabase;private $mediaDirectory;private $uploaderFactory;private $storeManager;private $logger;public $baseTmpPath;public $basePath;public $allowedExtensions;public function __construct(Database $coreFileStorageDatabase,Filesystem $filesystem,UploaderFactory $uploaderFactory,StoreManagerInterface $storeManager,LoggerInterface $logger){$this->coreFileStorageDatabase = $coreFileStorageDatabase;$this->mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);$this->uploaderFactory = $uploaderFactory;$this->storeManager = $storeManager;$this->logger = $logger;$this->baseTmpPath = "label/icon";$this->basePath = "label/icon";$this->allowedExtensions = ['jpg', 'jpeg', 'gif', 'png'];}public function setBaseTmpPath($baseTmpPath){$this->baseTmpPath = $baseTmpPath;}public function setBasePath($basePath){$this->basePath = $basePath;}public function setAllowedExtensions($allowedExtensions){$this->allowedExtensions = $allowedExtensions;}public function getBaseTmpPath(){return $this->baseTmpPath;}public function getBasePath(){return $this->basePath;}public function getAllowedExtensions(){return $this->allowedExtensions;}public function getFilePath($path, $imageName){return rtrim($path, '/') . '/' . ltrim($imageName, '/');}public function moveFileFromTmp($imageName){$baseTmpPath = $this->getBaseTmpPath();$basePath = $this->getBasePath();$baseImagePath = $this->getFilePath($basePath, $imageName);$baseTmpImagePath = $this->getFilePath($baseTmpPath, $imageName);try {$this->coreFileStorageDatabase->copyFile($baseTmpImagePath,$baseImagePath);$this->mediaDirectory->renameFile($baseTmpImagePath,$baseImagePath);} catch (\Exception $e) {throw new \Magento\Framework\Exception\LocalizedException(__('Something went wrong while saving the file(s).'));}return $imageName;}public function saveFileToTmpDir($fileId){$baseTmpPath = $this->getBaseTmpPath();$uploader = $this->uploaderFactory->create(['fileId' => $fileId]);$uploader->setAllowedExtensions($this->getAllowedExtensions());$uploader->setAllowRenameFiles(true);$result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath));if (!$result) {throw new \Magento\Framework\Exception\LocalizedException(__('File can not be saved to the destination folder.'));}$result['tmp_name'] = str_replace('\\', '/', $result['tmp_name']);$result['path'] = str_replace('\\', '/', $result['path']);$result['url'] = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . $this->getFilePath($baseTmpPath, $result['file']);$result['name'] = $result['file'];if (isset($result['file'])) {try {$relativePath = rtrim($baseTmpPath, '/') . '/' . ltrim($result['file'], '/');$this->coreFileStorageDatabase->saveFile($relativePath);} catch (\Exception $e) {$this->logger->critical($e);throw new \Magento\Framework\Exception\LocalizedException(__('Something went wrong while saving the file(s).'));}}return $result;}} - Create app/code/Vendor/Module/view/adminhtml/web/template/image-preview.html
1234567891011121314151617181920212223242526272829<div class="file-uploader-summary"><div class="file-uploader-preview"><a attr="href: $parent.getFilePreview($file)" target="_blank"><imgclass="preview-image"tabindex="0"event="load: $parent.onPreviewLoad.bind($parent)"attr="src: $parent.getFilePreview($file),alt: $file.name"></a><div class="actions"><buttontype="button"class="action-remove"data-role="delete-button"attr="title: $t('Delete image')"click="$parent.removeFile.bind($parent, $file)"><span translate="'Delete image'"/></button></div></div><div class="file-uploader-filename" text="$file.name"/><div class="file-uploader-meta"><text args="$file.previewWidth"/>x<text args="$file.previewHeight"/></div></div> - Create app/code/Vendor/Module/etc/di.xml
123456789101112<type name="Vendor\Module\Model\ImageUploader"><arguments><argument name="baseTmpPath" xsi:type="string">label/tmp/image</argument><argument name="basePath" xsi:type="string">label/image</argument><argument name="allowedExtensions" xsi:type="array"><item name="jpg" xsi:type="string">jpg</item><item name="jpeg" xsi:type="string">jpeg</item><item name="gif" xsi:type="string">gif</item><item name="png" xsi:type="string">png</item></argument></arguments></type>
That’s it.
Any doubts? Do mention them in the Comments section below. I’d be happy to help you out.
Also, do share the solution with the Magento Community via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
11 Comments
How to access this form from admin? code deployed not able to check from admin
please do check the log as its working well from our side.
Hello Shahbaz You need to add this code to your existing UI Form in admin side.
I want to show only image in UI Form(not uploading an image) can you please share how can i achieve this
Hello Vikram,
You can display the image by using the rendering class
You can use this blog as a reference: https://meetanshi.com/blog/use-grid-renderer-in-magento-2/
Thank You
Thanks for the article,
is this article enough for edit function also or do i need more workout to perform edit functionality?
Hello Mujahidh,
The above solution works for edit functionality as well.
Thank You
Warning: DOMXPath::query(): Invalid expression in /var/www/html/petzzcolocal/vendor/magento/framework/Config/Dom.php on line 336
Hello Bhargav,
It seems like you have mistaken something in copying or changing the class from your end as the above solution is working properly from our end.
Thank You
as it is applied code but still getting error “Notice: Trying to access array offset on value of type null in /var/www/html/magento2/vendor/magento/framework/File/Uploader.php on line 227”
Hello Ravi,
It seems like you’ve made some mistake while applying the above code.
Please check the whole code or send the complete code that you implemented.
Thank You