You can Add This
Add this code into From creation file
$fieldset->addField(
'image',
'image',
array(
'label' => 'Image',
'required' => false,
'name' => 'image',
'note' => 'Allow image type: jpg, jpeg, png',
)
);
Add This code into your Save From Data File
<?php
namespace [vendor_Name]\[Module_name]\Controller\Adminhtml\[controller_name];
use Magento\Backend\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Framework\Image\AdapterFactory;
class Save extends \Magento\Backend\App\Action
{
protected $fileSystem;
protected $uploaderFactory;
protected $request;
protected $adapterFactory;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Filesystem $fileSystem,
\Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory,
\Magento\Framework\App\RequestInterface $request,
AdapterFactory $adapterFactory
) {
parent::__construct($context);
$this->fileSystem = $fileSystem;
$this->request = $request;
$this->adapterFactory = $adapterFactory;
$this->uploaderFactory = $uploaderFactory;
}
public function execute()
{
$data = $this->getRequest()->getPostValue();
if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '')
{
try
{
$uploaderFactory = $this->uploaderFactory->create(['fileId' => 'image']);
$uploaderFactory->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$imageAdapter = $this->adapterFactory->create();
$uploaderFactory->addValidateCallback('custom_image_upload',$imageAdapter,'validateUploadFile');
$uploaderFactory->setAllowRenameFiles(true);
$uploaderFactory->setFilesDispersion(true);
$mediaDirectory = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA);
$destinationPath = $mediaDirectory->getAbsolutePath('[Folder_name]');
$result = $uploaderFactory->save($destinationPath);
if (!$result)
{
throw new LocalizedException
(
__('File cannot be saved to path: $1', $destinationPath)
);
}
$imagePath = '[Folder_Name]'.$result['file'];
$data['image'] = $imagePath;
}
catch (\Exception $e)
{
$this->messageManager->addError(__($e->getMessage()));
}
}
else
{
$this->messageManager->addError(__("Image not Save Pleae Try Again"));
$this->_redirect('*/*/index');
return;
}
if (!$data and $data['image'] == '')
{
$this->messageManager->addError(__("Data Not Save Pleae Try Again"));
$this->_redirect('*/*/index');
return;
}
try {
$rowData = $this->_objectManager->create('[vendor_Name]\[Module_name]\Model\locator');
$rowData->setData($data);
if (isset($data['id']))
{
$rowData->setId($data['id']);
$rowData->setStoreImage($data['image']);
}
$rowData->save();
$this->messageManager->addSuccess(__('Data has been successfully saved.'));
}
catch (\Exception $e)
{
$this->messageManager->addError(__($e->getMessage()));
}
$this->_redirect('*/*/index');
}
}
I Hope This Helps You.