SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH
How-to-Add-Custom-File-Upload-Control-in-Magento-2

Magento 2 Image Upload in System Configuration

In magento 2, one of the many fields you can add in configuration settings is image upload. In some cases, this is an extra feature in addition to your custom functionality

Magento 2 has many built-in functions that you just need to inherit to be able to use immediately .

In the following, I will guide you to add image upload functionality to magento 2’s backend module

First you need to have the system.xml file for your module. Let’s add it in the extension under the path Module\Name\etc

You can put it in different functional areas , so you just need to add the following code to your system.xml file , and correct it according to the name of the module you are working on

<field id="image" translate="label comment" type="image" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1" >
                    <label>Store Image</label>
               <backend_model>Module\Name\Model\Config\Backend\Image</backend_model>
                      <base_url type="media" scope_info="1">magepow/backendimage</base_url>
                </field>

As you can see file Module\Name\Model\Config\Backend\Image is called to handle the input field to upload the image , and magepow/backendimage is a folder created to add images after being saved in admin.

Following is a complete and simple system.xml file with some functions, in our example module and also the processing file for the Module\Name\Model\Config\Backend\Image section called above.

This is the module that we created to run name tests Magepow\SystemImage .

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="magepow" translate="label" sortOrder="1000">
            <label>Magepow</label>
        </tab>
        <section id="magepow_" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>System Image</label>
            <tab>magepow</tab>
            <resource>Magepow_SystemImage::config</resource>
            <group id="general" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>General Options</label>
                <field id="enabled" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Enabled</label>
                    <comment>Enable or disable module</comment>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
                <field id="image" translate="label comment" type="image" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1" >
                    <label>Store Image</label>
                    <backend_model>Magepow\SystemImage\Model\Config\Backend\Image</backend_model>
                      <base_url type="media" scope_info="1">magepow/backendimage</base_url>
                    <comment><![CDATA[Allowed file types: jpg, jpeg, gif, png, svg]]></comment>
                </field>
            </group>
        </section>
    </system>
</config>

And then, handle the inheritance and upload the image that we add to the backend module Magepow\SystemImage\Model\Config\Backend\Image

<?php
namespace Magepow\SystemImage\Model\Config\Backend;

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

    /**
     * Upload max file size in kilobytes
     *
     * @var int
     */
    protected $_maxFileSize = 20480;
    
   /**
     * 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']);
        $fileTmpName = $this->getTmpFileName();

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

Followed by the display for the function you just created. First let’s go to the helper that creates some functionality for the display.

Please add the Data file of your module to the path Magepow\SystemImage\Helper .

<?php

namespace Magepow\SystemImage\Helper;

use Magento\Store\Model\StoreManagerInterface;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{

    /**
     * @var array
     */
    protected $configModule;
    protected $_storeManager;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
           \Magento\Store\Model\StoreManagerInterface $storeManager
    )
    {
        parent::__construct($context);
        $this->configModule = $this->getConfig(strtolower($this->_getModuleName()));
         $this->_storeManager = $storeManager;
    }

    public function getConfig($cfg='')
    {
        if($cfg) return $this->scopeConfig->getValue( $cfg, \Magento\Store\Model\ScopeInterface::SCOPE_STORE );
        return $this->scopeConfig;
    }

    public function getConfigModule($cfg='', $value=null)
    {
        $values = $this->configModule;
        if( !$cfg ) return $values;
        $config  = explode('/', $cfg);
        $end     = count($config) - 1;
        foreach ($config as $key => $vl) {
            if( isset($values[$vl]) ){
                if( $key == $end ) {
                    $value = $values[$vl];
                }else {
                    $values = $values[$vl];
                }
            } 

        }
        return $value;
    }

    public function getBaseUrlMedia()
    {
       return $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
    }

}

Please add this to your .phtml file to your block

<?php 
    $helper = $this->helper('Magepow\SystemImage\Helper\Data');
    $imgSystem = $helper->getConfigModule('general/image');
    $urlMedia = $helper->getBaseUrlMedia();
    $enabledModule = $helper->getConfigModule('general/enabled');
?>
<?php if(!$enabledModule) return; ?>
<div class="image-system-wishlist"><img src="<?php echo $urlMedia.'magepow/backendimage/'. $imgSystem?>" ></div>

Have any questions or ideas about the article, please comment on the article and I will reply as soon as possible. Thanks