I am trying to upload a file(mostly likely image) from customer registration form.
What have I done till now
- Create file type field on customer registration form
- 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