Magento 2- Create image upload button in admin form

Magento 2- Create image upload button in admin form-

Step 1:Create form.php file, and use this code to add image upload button-

Path– app\code\Vendor\Modulename\Block\Adminhtml\[Entity]\Edit\Tab


$fieldset->addField(
'image',
'image',

array(
'name' => 'image',
'label' => __('Image'),
'title' => __('Image'),
/*'required' => true*/
)
);

Step 2:Inside save.php action in  your admin controller directory

Use this code inside Class-


/**
* @var \Magento\Framework\View\Result\PageFactory
*/

/**
* @param \Magento\Framework\App\Action\Context $context

*/

public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory

) {

$this->_fileUploaderFactory = $fileUploaderFactory;
parent::__construct($context);

}

Use this code inside execute-

if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {

try {
$uploader = $this->_fileUploaderFactory->create(array('fileId' => 'image'));
$uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);

$mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')
->getDirectoryRead(DirectoryList::MEDIA);
$result = $uploader->save($mediaDirectory->getAbsolutePath('/images'));
$data['image'] = $_FILES['image']['name'];

} catch (Exception $e) {
$data['image'] = $_FILES['image']['name'];
}
}
else{
$data['image'] = $data['image']['value'];
}