4

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

9
  • ...can you send me your module file Feb 14, 2017 at 11:50
  • Why do you want it?? Feb 14, 2017 at 12:17
  • i want to this regarding customers can upload their image during registration can you send me file here Feb 14, 2017 at 12:38
  • Sending files here is not feasible please share your email address and i will email you my module Feb 15, 2017 at 4:00
  • thanks bro kindly send me on [email protected] Feb 15, 2017 at 4:27

1 Answer 1

3
<?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('/');
    }
}
1
  • What about guest users who later registers after order placement?
    – MagePsycho
    Apr 6, 2017 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.