How to Add Image Upload Field in System Configuration in magento2
Steps to Add Image Upload Field in Magento 2 System Configuration:
Step 1: Initially, you need to create a field in the system.xml file, at the path given below.
app/code/Vendor/Extension/etc/adminhtml/system.xml
Use the following code snippet
<field id="image" translate="label" type="image" sortOrder="20" showInDefault="1" showInWebsite="1">
<label>Upload Image</label>
<backend_model>Vendor\Extension\Model\Config\Backend\Image</backend_model>
<base_url type="media">extensionname/foldername/</base_url>
</field>
Step 2: Next you need to backend the model file Image.php. For that go to the below path
Vendor\Extension\Model\Config\Backend\Image.php
And add the code as follows
<?php
namespace Vendor\Extension\Model\Config\Backend;
class Image extends \Magento\Config\Model\Config\Backend\Image
{
const UPLOAD_DIR = 'yourfolder';
/**
* 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));
}
protected function _addWhetherScopeInfo()
{
return true;
}
/**
* Getter for allowed extensions of uploaded files.
*
* @return string[]
*/
protected function _getAllowedExtensions()
{
return ['jpg', 'jpeg', 'gif', 'png', 'svg'];
}
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;
}
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();
}
private function isTmpFileAvailable($value)
{
return is_array($value) && isset($value[0]['tmp_name']);
}
private function getUploadedImageName($value)
{
if (is_array($value) && isset($value[0]['name']))
{
return $value[0]['name'];
}
return '';
}
}
Once you perform the above steps successfully, the image upload field is added to Magento 2 system configuration.
Comments
Post a Comment