Magento 2 Admin custom form image upload.

Step 1: Add Below code in n _prepareForm() function inside

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

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

Step 2:
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('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']);
        $imageAdapterFactory = $this->_objectManager->get('Magento\Framework\Image\AdapterFactory')
            ->create();
        $uploader->setAllowRenameFiles(true);
        $uploader->setFilesDispersion(true);
        $uploader->setAllowCreateFolders(true);
        $mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')
            ->getDirectoryRead(DirectoryList::MEDIA);

        $result = $uploader->save(
            $mediaDirectory
                ->getAbsolutePath('Modulename/Image')
        );
        $model->setProfile('Modulename/Image'.$result['file']); //Database field name
    } catch (\Exception $e) {
        if ($e->getCode() == 0) {
            $this->messageManager->addError($e->getMessage());
        }
    }
}
Create your website at WordPress.com
Get started