Magento, Magento 2

How to Add Image Upload in Magento 2 Configuration

How to Add Image Upload in Magento 2 Configuration

In this tutorial, Today I will explain how to add image upload in Magento 2 Store Configuration. Using Image Uploader you can add image with different image image types.

So, Let’s start to add image upload store configuration.

You may also like this :

1) First of all, Let’s assume that you have created simple module. Add this below code in your system.xml file to add image upload to store configuration at this file path app/code/RH/Helloworld/etc/adminhtml/ :

<field id="image_upload" translate="label" type="image" sortOrder="60" showInDefault="1" showInWebsite="1" showInStore="1">
    <label>Image Upload</label>
    <backend_model>RH\Helloworld\Model\Config\Backend\Image</backend_model>
    <base_url type="media" scope_info="1">helloworld</base_url><!-- Add Your Image Directory Name. It will be display pub/media/helloworld -->
    <comment><![CDATA[Allowed file types: jpg, jpeg, gif, png, svg]]></comment>
</field>

2) After that, Create backend model file Image.php at this file path app/code/RH/Helloworld/Model/Config/Backend :

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Model\Config\Backend;

class Image extends \Magento\Config\Model\Config\Backend\Image
{
    /**
     * The tail part of directory path for uploading
     */
    const UPLOAD_DIR = 'helloworld';

    /**
     * Upload max file size in kilobytes
     *
     * @var int
     */
    protected $_maxFileSize = 2048;
    
   /**
     * Return path to directory for upload file
     *
     * @return string
     * @throw \Magento\Framework\Exception\LocalizedException
     */
    protected function _getUploadDir()
    {
        return $this->_mediaDirectory->getAbsolutePath($this->_appendScopeInfo(self::UPLOAD_DIR));
    }

    /**
     * Makes a decision about whether to add info about the scope.
     *
     * @return boolean
     */
    protected function _addWhetherScopeInfo()
    {
        return true;
    }

    /**
     * Getter for allowed extensions of uploaded files.
     *
     * @return string[]
     */
    protected function _getAllowedExtensions()
    {
        return ['jpg', 'jpeg', 'gif', 'png', 'svg'];
    }

    /**
     * @return string|null
     */
    protected function getTmpFileName()
    {
        $tmpName = null;
        if (isset($_FILES['groups'])) {
            $tmpName = $_FILES['groups']['tmp_name'][$this->getGroupId()]['fields'][$this->getField()]['value'];
        } else {
            $tmpName = is_array($this->getValue()) ? $this->getValue()['tmp_name'] : null;
        }
        return $tmpName;
    }

    /**
     * Save uploaded file before saving config value
     *
     * Save changes and delete file if "delete" option passed
     *
     * @return $this
     */
    public function beforeSave()
    {
        $value = $this->getValue();
        $deleteFlag = is_array($value) && !empty($value['delete']);
        if ($this->isTmpFileAvailable($value) && $imageName = $this->getUploadedImageName($value)) {
            $fileTmpName = $this->getTmpFileName();

            if ($this->getOldValue() && ($fileTmpName || $deleteFlag)) {
                $this->_mediaDirectory->delete(self::UPLOAD_DIR . '/' . $this->getOldValue());
            }
        }
        return parent::beforeSave();
    }

    /**
     * Check if temporary file is available for new image upload.
     *
     * @param array $value
     * @return bool
     */
    private function isTmpFileAvailable($value)
    {
        return is_array($value) && isset($value[0]['tmp_name']);
    }

    /**
     * Gets image name from $value array.
     *
     * Will return empty string in a case when $value is not an array.
     *
     * @param array $value Attribute value
     * @return string
     */
    private function getUploadedImageName($value)
    {
        if (is_array($value) && isset($value[0]['name'])) {
            return $value[0]['name'];
        }

        return '';
    }
}

That’s it !!!

You can set image types in _getAllowedExtensions() function which you want to allow in image uploader in configuration field. In this example, I set custom folder name as “helloworld”. You can set folder name as per your requirement.

In Last, Just clean cache using below command and check it :

I hope this blog is easy to understand about add image upload in Magento 2 Store Configuration. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Keep liking and sharing !!

Tagged ,