fileUploaderFactory = $fileUploaderFactory; $this->customerMetadataService = $customerMetadataService; $this->logger = $logger; parent::__construct($context); } /** * @inheritDoc */ public function execute() { try { if (empty($_FILES)) { throw new \Exception('$_FILES array is empty.'); } $attributeCode = key($_FILES['customer']['name']); $attributeMetadata = $this->customerMetadataService->getAttributeMetadata($attributeCode); /** @var FileUploader $fileUploader */ $fileUploader = $this->fileUploaderFactory->create([ 'attributeMetadata' => $attributeMetadata, 'entityTypeCode' => CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER, 'scope' => 'customer', ]); $errors = $fileUploader->validate(); if (true !== $errors) { $errorMessage = implode('
', $errors); throw new LocalizedException(__($errorMessage)); } $result = $fileUploader->upload(); } catch (LocalizedException $e) { $result = [ 'error' => $e->getMessage(), 'errorcode' => $e->getCode(), ]; } catch (\Exception $e) { $this->logger->critical($e); $result = [ 'error' => __('Something went wrong while saving file.'), 'errorcode' => $e->getCode(), ]; } /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON); $resultJson->setData($result); return $resultJson; } }