Magento 2 Customer Registration – Upload a File on Customer Registration Page

magento-2.1magento2

I am trying to upload a file(mostly likely image) from customer registration form.

What have I done till now

  1. Create file type field on customer registration form
  2. Created a module that observe the event for customer register success.

Observer code:

<?php 


namespace Custom\Customergroup\Observer\Customer;
// added by me
use Magento\Customer\Api\CustomerRepositoryInterface;




class RegisterSuccess implements \Magento\Framework\Event\ObserverInterface {

/**
     * @var CustomerRepositoryInterface
     */
//added by me
    private $customerRepository;

    public function __construct(
        \Magento\Framework\App\RequestInterface $request,
         CustomerRepositoryInterface $customerRepository
        )
    {
        $this->_request = $request;
        $this->customerRepository = $customerRepository;
    }
    //ends here
    public function execute(
        \Magento\Framework\Event\Observer $observer
    ){      

        $id = $observer->getEvent()->getCustomer()->getId();
        $customer = $this->customerRepository->getById($id);
        //get files uploaded
        if (isset($_FILES['fileToUpload']['name']) && $_FILES['fileToUpload']['name'] != "") {
                    die('here');
                }
                else{
                    die('there');
                }

        //  $group_id = $this->_request->getParam('group_id');

        // $customer->setGroupId($group_id);

        $this->customerRepository->save($customer);

    }
}

In Magento 1.x

We could do something like this:

public function handle_file_upload($observer)
        {
                $customer = $observer->getCustomer();
                if (isset($_FILES['prooffile']['name']) && $_FILES['prooffile']['name'] != "") {
                                $uploader = new Varien_File_Uploader("prooffile");
                                $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png', 'pdf'));
                                $uploader->setAllowRenameFiles(false);
                                $uploader->setFilesDispersion(false);
                                $path = Mage::getBaseDir("media") . DS . "customer" . DS;
                                $logoName = $customer->getId() . "." . pathinfo($_FILES['prooffile']['name'], PATHINFO_EXTENSION);
                                $uploader->save($path, $logoName);
                                $customer->setProoffile($logoName);
                                $customer->save();
                }
        }

I just want to know how to achieve this on Magento 2.

Thanks

Best Answer

<?php 
namespace Custom\Customergroup\Observer\Customer;

use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;

class RegisterSuccess implements \Magento\Framework\Event\ObserverInterface {

    /**
     * @var CustomerRepositoryInterface
     */
    private $customerRepository;

    protected $uploaderFactory;

    protected $fileSystem;

    protected $fileId = 'your_file_id';
    protected $allowedExtensions = ['jpg', 'png'];

    public function __construct(
        \Magento\Framework\App\RequestInterface $request,
        CustomerRepositoryInterface $customerRepository,
        UploaderFactory $uploaderFactory,
        Filesystem $fileSystem
    )
    {
        $this->_request = $request;
        $this->customerRepository = $customerRepository;
        $this->uploaderFactory = $uploaderFactory;
        $this->fileSystem = $fileSystem;
    }

    public function execute(\Magento\Framework\Event\Observer $observer){      

        $id = $observer->getEvent()->getCustomer()->getId();
        $customer = $this->customerRepository->getById($id);
        //get files uploaded
        if (isset($_FILES['fileToUpload']['name']) && $_FILES['fileToUpload']['name'] != "") {
            $destinationPath = $this->getDestinationPath();
            try {
                $uploader = $this->uploaderFactory->create(['fileId' => $this->fileId])
                    ->setAllowCreateFolders(true)
                    ->setAllowRenameFiles(true)
                    ->setAllowedExtensions($this->allowedExtensions);

                if (!$fileData = $uploader->save($destinationPath)) {
                    throw new LocalizedException(
                        __('File cannot be saved to path: $1', $destinationPath)
                    );
                }
                //$fileName = $fileData['file'];
            } catch (\Exception $e) {
                $message = $this->messageManager->addError(
                    __($e->getMessage())
                );
                die;
            }
        } else{
            die('there');
        }

        $this->customerRepository->save($customer);

    }

    public function getDestinationPath()
    {
        return $this->fileSystem
            ->getDirectoryWrite(DirectoryList::MEDIA)
            ->getAbsolutePath('/');
    }
}
Related Topic