_objectManager = $objectManager; $this->_httpRequest = $context->getRequest(); } public function uploadImage($type, $data, $mediaFolder, $allowedExtensions = '', $maximumSize = 0) { $mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')->getDirectoryRead(DirectoryList::MEDIA); $imagePath = $mediaDirectory->getAbsolutePath(); if (isset($data[$type]['delete'])) { $imagePath .= isset($data[$type]['value']) ? $data[$type]['value'] : $data[$type]; if ($imagePath != $mediaDirectory && file_exists($imagePath)) { unlink($imagePath); } $data[$type] = ''; } $image = $this->_httpRequest->getFiles($type); if (isset($image['error']) && $image['error'] == 0) { if ($imagePath) { if ($imagePath != $mediaDirectory && file_exists($imagePath) && $imagePath != $mediaDirectory->getAbsolutePath()) { unlink($imagePath); } } if ($maximumSize && $image['size'] > $maximumSize) { throw new \Magento\Framework\Exception\ValidatorException(__('The file is too large. Maximum upload file size: %1MB', $maximumSize/1000000)); } $savePath = $mediaDirectory->getAbsolutePath($mediaFolder); $uploader = $this->_objectManager->create( 'Magento\Framework\File\Uploader', array('fileId' => $type) ); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(false); if ($allowedExtensions) { $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); } $file = $uploader->save($savePath); $data[$type] = $mediaFolder . '/' . $file['name']; $data[$type] = str_replace('//', '/', $data[$type]); } else if (isset($data[$type]) && is_array($data[$type])) { $data[$type] = $data[$type]['value']; } return $data; } }