Magento 2 allow you to add custom field form as type image , for example when you click in edit link inisde grid you have edit page you can add from fiedl :
$fieldset->addField( 'image', 'image', [ 'title' => __('Image'), 'label' => __('Image'), 'name' => 'image', 'note' => 'Allow image type: jpg, jpeg, gif, png', ] );
So now you have your field , you can use your controller to save the image inside media , now inject (\Magento\Framework\Image\AdapterFactory $adapterFactory,\Magento\MediaStorage\Model\File\UploaderFactory $uploader):
/** * @var \Magento\Framework\Image\AdapterFactory */ protected $adapterFactory; /** * @var \Magento\MediaStorage\Model\File\UploaderFactory */ protected $uploader; /** * @var \Magento\Framework\Filesystem */ protected $filesystem; /** * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface */ protected $timezoneInterface; public function __construct(Action\Context $context,\Magento\Framework\Image\AdapterFactory $adapterFactory,\Magento\MediaStorage\Model\File\UploaderFactory $uploader,\Magento\Framework\Filesystem $filesystem) { $this->adapterFactory = $adapterFactory; $this->uploader = $uploader; $this->filesystem = $filesystem; parent::__construct($context); }
inisde your execute() method :
/** * Save action * * @return \Magento\Framework\Controller\ResultInterface */ public function execute() { …............ //start block upload image /* * Save image upload */ try { $base_media_path = 'ibnab/owlsliders/images'; $uploader = $this->uploader->create( ['fileId' => 'image'] ); $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']); $imageAdapter = $this->adapterFactory->create(); $uploader->addValidateCallback('image', $imageAdapter, 'validateUploadFile'); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(true); $mediaDirectory = $this->filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA); $result = $uploader->save( $mediaDirectory->getAbsolutePath(base_media_path) ); $data['image'] = base_media_path.$result['file']; } catch (\Exception $e) { if ($e->getCode() == 0) { $this->messageManager->addError($e->getMessage()); } } } else { $data['image'] = null; $data['delete_image'] = true; $data['image'] = $data['image']['value']; } else { $data['image'] = null; } } } //end block upload image …................ }
with simple code you upload the image and you try if delete is checked (if true it will be deleted)
Comments