How to create beautiful image upload in configuration of Magento 2
To create beautiful image upload in configuration of Magento 2, add the following code in system.xml:
1 2 3 4 5 |
<field id="upload_image_id" translate="label comment" type="image" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Select Image</label> <backend_model>NameSpace\YourModule\Model\Config\Backend\Image</backend_model> <base_url type="media" scope_info="1">yourfolder</base_url> </field> |
And it is also necessary to create a custom model in system.xml:
NameSpace\YourModule\Model\Config\Backend\Image.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<?php namespace NameSpace\YourModule\Model\Config\Backend; class Image extends \Magento\Config\Model\Config\Backend\Image { /** * The tail part of directory path for uploading * */ const UPLOAD_DIR = 'yourfolder'; // Folder save image /** * 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']; } |
Source (