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 $addressMetadataService;
35 
39  private $logger;
40 
47  public function __construct(
48  Context $context,
49  FileUploaderFactory $fileUploaderFactory,
50  AddressMetadataInterface $addressMetadataService,
51  LoggerInterface $logger
52  ) {
53  $this->fileUploaderFactory = $fileUploaderFactory;
54  $this->addressMetadataService = $addressMetadataService;
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  // Must be executed before any operations with $_FILES!
70  $this->convertFilesArray();
71 
72  $attributeCode = key($_FILES['address']['name']);
73  $attributeMetadata = $this->addressMetadataService->getAttributeMetadata($attributeCode);
74 
76  $fileUploader = $this->fileUploaderFactory->create([
77  'attributeMetadata' => $attributeMetadata,
79  'scope' => 'address',
80  ]);
81 
82  $errors = $fileUploader->validate();
83  if (true !== $errors) {
84  $errorMessage = implode('</br>', $errors);
85  throw new LocalizedException(__($errorMessage));
86  }
87 
88  $result = $fileUploader->upload();
89  } catch (LocalizedException $e) {
90  $result = [
91  'error' => $e->getMessage(),
92  'errorcode' => $e->getCode(),
93  ];
94  } catch (\Exception $e) {
95  $this->logger->critical($e);
96  $result = [
97  'error' => __('Something went wrong while saving file.'),
98  'errorcode' => $e->getCode(),
99  ];
100  }
101 
103  $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
104  $resultJson->setData($result);
105  return $resultJson;
106  }
107 
115  private function convertFilesArray()
116  {
117  foreach ($_FILES['address'] as $itemKey => $item) {
118  foreach ($item as $value) {
119  if (is_array($value)) {
120  $_FILES['address'][$itemKey] = [
121  key($value) => current($value),
122  ];
123  }
124  }
125  }
126  }
127 }
__()
Definition: __.php:13
$logger
$value
Definition: gender.phtml:16
$attributeCode
Definition: extend.phtml:12
__construct(Context $context, FileUploaderFactory $fileUploaderFactory, AddressMetadataInterface $addressMetadataService, LoggerInterface $logger)
Definition: Upload.php:47
$errors
Definition: overview.phtml:9