Question:

How to do image uploader in the custom form field in magento 2 backend

Leah: 2 weeks ago

How to do image uploader in the custom form field in magento 2 backen

 _prepareForm()

$fieldset->addField(
            'proimage',
            'image',
            [
                'title' => __('Image'),
                'label' => __(' Image'),
                'name' => 'proimage',
                'note' => 'Allow image type: jpg, jpeg, gif, png',
            ]
        );

Save.php controller

 <?php

    namespace Cm\Productlabel\Controller\Adminhtml\Label;
    use Magento\Backend\App\Action;
    use Magento\Framework\App\Filesystem\DirectoryList;

    class Save extends Action
    {
        /**
         * @param Action\Context $context
         */

        public function __construct(
          Action\Context $context,
       )
        {
            parent::__construct($context);

        }


        protected function _isAllowed()
        {
            return $this->_authorization->isAllowed('Cm_Productlabel::save');
        }


       public function execute()
       {
          $isPost = $this->getRequest()->getPost();
          $resultRedirect = $this->resultRedirectFactory->create();
          if ($isPost) {
                $model = $this->_objectManager- 
              >create('Cm\Productlabel\Model\Productlabel');
             $postId = $this->getRequest()->getParam('productlabel_id');

             if ($postId) {
                $model->load($postId);
             }
            $profileImage = $this->getRequest()->getFiles('proimage');
       $fileName = ($profileImage && array_key_exists('name', $profileImage)) ? 
        $profileImage['name'] : null;
    if ($profileImage && $fileName) {
        try {


            $uploader = $this->_objectManager->create(
                'Magento\MediaStorage\Model\File\Uploader',
                ['fileId' => 'proimage']
            );
            $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
            /** @var \Magento\Framework\Image\Adapter\AdapterInterface 
          $imageAdapterFactory */
            $imageAdapterFactory = $this->_objectManager- 
           >get('Magento\Framework\Image\AdapterFactory')
                ->create();
            $uploader->setAllowRenameFiles(true);
            $uploader->setFilesDispersion(true);
            $uploader->setAllowCreateFolders(true);
            /** @var \Magento\Framework\Filesystem\Directory\Read 
             $mediaDirectory */
            $mediaDirectory = $this->_objectManager- 
                  >get('Magento\Framework\Filesystem')
                ->getDirectoryRead(DirectoryList::MEDIA);

            $result = $uploader->save(
                $mediaDirectory
                    ->getAbsolutePath('Bootsgrid/Productlabel')
            );
            //$data['profile'] = 'Modulename/Profile/'. $result['file'];
            $model->setProimage('Bootsgrid/Productlabel'.$result['file']); / 
            /Database field name
        } catch (\Exception $e) {
            if ($e->getCode() == 0) {
                $this->messageManager->addError($e->getMessage());
            }
          }
          }

             $formData = $this->getRequest()->getParam('label');
             $model->setData($formData);

             try {

                // Save news
                $model->save();

                // Display success message
                $this->messageManager->addSuccess(__('The post has been 
                 saved.'));

                // Check if 'Save and Continue'
                if ($this->getRequest()->getParam('back')) {
                   $this->_redirect('*/*/edit', ['id' => $model->getId(), 
               '_current' => true]);
                   return;
                }

                // Go to grid page
                $this->_redirect('*/*/');
                return;
             } catch (\Exception $e) {
                $this->messageManager->addError($e->getMessage());
             }

             $this->_getSession()->setFormData($formData);
             $this->_redirect('*/*/edit', ['id' => $postId]);
          }
       }

    }

Answer:
Natalie: 2 weeks ago

Add Below code in n _prepareForm() function inside

app/code/Vendor/Module/Block/Adminhtml/Module/Edit/Tab/Main.php

$fieldset->addField(
    'profile',
    'image',
    [
        'name' => 'profile',
        'label' => __('Profile Image'),
        'title' => __('Profile Image'),
        'required'  => false,
        'disabled' => $isElementDisabled
    ]
);

Now in execute() method of your save controller file. use below code to save and upload image.

app/code/Vendor/Module/Controller/Adminhtml/Index/Save.php

use Magento\Framework\App\Filesystem\DirectoryList;

$profileImage = $this->getRequest()->getFiles('profile');
$fileName = ($profileImage && array_key_exists('name', $profileImage)) ? $profileImage['name'] : null;
if ($profileImage && $fileName) {
    try {
        /** @var \Magento\Framework\ObjectManagerInterface $uploader */
        $uploader = $this->_objectManager->create(
            'Magento\MediaStorage\Model\File\Uploader',
            ['fileId' => 'profile']
        );
        $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
        /** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapterFactory */
        $imageAdapterFactory = $this->_objectManager->get('Magento\Framework\Image\AdapterFactory')
            ->create();
        $uploader->setAllowRenameFiles(true);
        $uploader->setFilesDispersion(true);
        $uploader->setAllowCreateFolders(true);
        /** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */
        $mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')
            ->getDirectoryRead(DirectoryList::MEDIA);

        $result = $uploader->save(
            $mediaDirectory
                ->getAbsolutePath('Modulename/Profile')
        );
        //$data['profile'] = 'Modulename/Profile/'. $result['file'];
        $model->setProfile('Modulename/Profile'.$result['file']); //Database field name
    } catch (\Exception $e) {
        if ($e->getCode() == 0) {
            $this->messageManager->addError($e->getMessage());
        }
    }
}

And Image showing in grid follow this link : Reference (https://magento.stackexchange.com/a/269523/68695)