cancel
Showing results for 
Search instead for 
Did you mean: 

Magento 2 : How to save Customer Attribute with input type file/Image ??

Magento 2 : How to save Customer Attribute with input type file/Image ??

Hello Community, 

 

I am trying to save customer attribute which is Image Type.

 

But, I can able to save Customer Object but it can't able to render image at Admin Customer View.

 

Image is also store is given Directory .

Below is my observer code, I have used event customer_register_success.

 

Vendor/Module/Observer/CustomerRegisterSuccess.php

 

 

<?php
 namespace Inchoo\Helloworld\Observer;

 use Magento\Framework\Event\ObserverInterface;
 use Magento\Framework\Event\Observer;
 use Magento\Framework\App\Filesystem\DirectoryList;
 use Magento\Customer\Api\CustomerRepositoryInterface;

 class CustomerRegisterSuccess implements ObserverInterface
 {
/** @var CustomerRepositoryInterface */
protected $customerRepository;
protected $adapterFactory;
protected $uploaderFactory;
protected $filesystem;
protected $_request;

/**
 * @param CustomerRepositoryInterface $customerRepository
 */
public function __construct(
    CustomerRepositoryInterface $customerRepository,
    \Magento\Framework\App\RequestInterface $request,
    \Magento\Framework\Filesystem $filesystem,
    \Magento\Framework\Image\AdapterFactory $adapterFactory,
    \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory
) {
    $this->customerRepository = $customerRepository;
    $this->_request = $request;
    $this->filesystem = $filesystem;
    $this->adapterFactory = $adapterFactory;
    $this->uploaderFactory = $uploaderFactory;
}

/**
 * Manages redirect
 */
public function execute(Observer $observer)
{
    $accountController = $observer->getAccountController();
    $customer = $observer->getCustomer();
    $request = $accountController->getRequest();


    /* Zero Start */
    $uploaderFactory = $this->uploaderFactory->create(['fileId' => 'profileimage']);
    $uploaderFactory->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
    $imageAdapter = $this->adapterFactory->create();
    $uploaderFactory->setAllowRenameFiles(true);
    $uploaderFactory->setFilesDispersion(true);
    $mediaDirectory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
    $destinationPath = $mediaDirectory->getAbsolutePath('Customer_Image');
    $result = $uploaderFactory->save($destinationPath); 

    /* Zero End */

   // print_r($result);
    $customerAvatar = $result['file'];

    $customer->setCustomAttribute('customer_avatar', $customerAvatar);
    $this->customerRepository->save($customer);
  }
 }

Any help would be appreciated.