Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Upload.php
Go to the documentation of this file.
1 <?php
7 
12 use Magento\Customer\Model\FileUploaderFactory;
15 use Psr\Log\LoggerInterface;
16 
17 class Upload extends Action
18 {
24  const ADMIN_RESOURCE = 'Magento_Customer::manage';
25 
29  private $fileUploaderFactory;
30 
34  private $customerMetadataService;
35 
39  private $logger;
40 
47  public function __construct(
48  Context $context,
49  FileUploaderFactory $fileUploaderFactory,
50  CustomerMetadataInterface $customerMetadataService,
51  LoggerInterface $logger
52  ) {
53  $this->fileUploaderFactory = $fileUploaderFactory;
54  $this->customerMetadataService = $customerMetadataService;
55  $this->logger = $logger;
56  parent::__construct($context);
57  }
58 
62  public function execute()
63  {
64  try {
65  if (empty($_FILES)) {
66  throw new \Exception('$_FILES array is empty.');
67  }
68 
69  $attributeCode = key($_FILES['customer']['name']);
70  $attributeMetadata = $this->customerMetadataService->getAttributeMetadata($attributeCode);
71 
73  $fileUploader = $this->fileUploaderFactory->create([
74  'attributeMetadata' => $attributeMetadata,
76  'scope' => 'customer',
77  ]);
78 
79  $errors = $fileUploader->validate();
80  if (true !== $errors) {
81  $errorMessage = implode('</br>', $errors);
82  throw new LocalizedException(__($errorMessage));
83  }
84 
85  $result = $fileUploader->upload();
86  } catch (LocalizedException $e) {
87  $result = [
88  'error' => $e->getMessage(),
89  'errorcode' => $e->getCode(),
90  ];
91  } catch (\Exception $e) {
92  $this->logger->critical($e);
93  $result = [
94  'error' => __('Something went wrong while saving file.'),
95  'errorcode' => $e->getCode(),
96  ];
97  }
98 
100  $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
101  $resultJson->setData($result);
102  return $resultJson;
103  }
104 }
__()
Definition: __.php:13
$logger
$attributeCode
Definition: extend.phtml:12
__construct(Context $context, FileUploaderFactory $fileUploaderFactory, CustomerMetadataInterface $customerMetadataService, LoggerInterface $logger)
Definition: Upload.php:47
$errors
Definition: overview.phtml:9