Magento – Adding image upload field to admin form

adminimage-uploadmagento2

I'm trying to add an image upload field to the admin module form so admin users can have a profile picture, I've managed to add a column in the database through the installSchema but can't work out how to add the upload button and save the image on the frontend.

Can anyone point me in the right direction?

Best Answer

Add Below code in n _prepareForm() function inside

app/code/Namespace/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/Namespace/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());
        }
    }
}
Related Topic