/** * Save uploaded file before saving config value * * @return $this * @throws \Magento\Framework\Exception\LocalizedException */ public function beforeSave() { $value = $this->getValue(); $file = $this->getFileData(); if (!empty($file)) { $uploadDir = $this->_getUploadDir(); try { /** @var Uploader $uploader */ $uploader = $this->_uploaderFactory->create(['fileId' => $file]); $uploader->setAllowedExtensions($this->_getAllowedExtensions()); $uploader->setAllowRenameFiles(true); $uploader->addValidateCallback('size', $this, 'validateMaxSize'); $result = $uploader->save($uploadDir); } catch (\Exception $e) { throw new \Magento\Framework\Exception\LocalizedException(__('%1', $e->getMessage())); } $filename = $result['file']; if ($filename) { if ($this->_addWhetherScopeInfo()) { $filename = $this->_prependScopeInfo($filename); } $this->setValue($filename); } } else { if (is_array($value) && !empty($value['delete'])) { $this->setValue(''); } else { $this->unsValue(); } } return $this; }
/** * After save * * @param \Magento\Framework\DataObject $object * @return $this|void */ public function afterSave($object) { $value = $object->getData($this->getAttribute()->getName()); if (is_array($value) && !empty($value['delete'])) { $object->setData($this->getAttribute()->getName(), ''); $this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName()); return; } try { /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */ $uploader = $this->_fileUploaderFactory->create(['fileId' => $this->getAttribute()->getName()]); $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(true); } catch (\Exception $e) { return $this; } $path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('catalog/product/'); $uploader->save($path); $fileName = $uploader->getUploadedFileName(); if ($fileName) { $object->setData($this->getAttribute()->getName(), $fileName); $this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName()); } return $this; }
/** * Image upload action in iframe * * @return string */ public function execute() { try { $uploader = $this->uploaderFactory->create(['fileId' => 'datafile']); $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']); /** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapter */ $imageAdapter = $this->adapterFactory->create(); $uploader->addValidateCallback('catalog_product_image', $imageAdapter, 'validateUploadFile'); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(true); /** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */ $mediaDirectory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA); $config = $this->config; $result = $uploader->save($mediaDirectory->getAbsolutePath($config->getBaseTmpMediaPath())); $this->_eventManager->dispatch('swatch_gallery_upload_image_after', ['result' => $result, 'action' => $this]); unset($result['tmp_name']); unset($result['path']); $result['url'] = $this->config->getTmpMediaUrl($result['file']); $result['file'] = $result['file'] . '.tmp'; $newFile = $this->swatchHelper->moveImageFromTmp($result['file']); $this->swatchHelper->generateSwatchVariations($newFile); $fileData = ['swatch_path' => $this->swatchHelper->getSwatchMediaUrl(), 'file_path' => $newFile]; $this->getResponse()->setBody(json_encode($fileData)); } catch (\Exception $e) { $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()]; $this->getResponse()->setBody(json_encode($result)); } }
/** * Upload file controller action * * @return \Magento\Framework\Controller\ResultInterface */ public function executeInternal() { $type = $this->getRequest()->getParam('type'); $tmpPath = ''; if ($type == 'samples') { $tmpPath = $this->_sample->getBaseTmpPath(); } elseif ($type == 'links') { $tmpPath = $this->_link->getBaseTmpPath(); } elseif ($type == 'link_samples') { $tmpPath = $this->_link->getBaseSampleTmpPath(); } try { $uploader = $this->uploaderFactory->create(['fileId' => $type]); $result = $this->_fileHelper->uploadFromTmp($tmpPath, $uploader); if (!$result) { throw new \Exception('File can not be moved from temporary folder to the destination folder.'); } /** * Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS */ $result['tmp_name'] = str_replace('\\', '/', $result['tmp_name']); $result['path'] = str_replace('\\', '/', $result['path']); if (isset($result['file'])) { $relativePath = rtrim($tmpPath, '/') . '/' . ltrim($result['file'], '/'); $this->storageDatabase->saveFile($relativePath); } $result['cookie'] = ['name' => $this->_getSession()->getName(), 'value' => $this->_getSession()->getSessionId(), 'lifetime' => $this->_getSession()->getCookieLifetime(), 'path' => $this->_getSession()->getCookiePath(), 'domain' => $this->_getSession()->getCookieDomain()]; } catch (\Exception $e) { $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()]; } return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result); }
/** * Save uploaded file and set its name to category * * @param \Magento\Framework\DataObject $object * @return \Magento\Catalog\Model\Category\Attribute\Backend\Image */ public function afterSave($object) { $value = $object->getData($this->getAttribute()->getName() . '_additional_data'); // if no image was set - nothing to do if (empty($value) && empty($_FILES)) { return $this; } if (is_array($value) && !empty($value['delete'])) { $object->setData($this->getAttribute()->getName(), ''); $this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName()); return $this; } $path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('catalog/category/'); try { /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */ $uploader = $this->_fileUploaderFactory->create(['fileId' => $this->getAttribute()->getName()]); $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']); $uploader->setAllowRenameFiles(true); $result = $uploader->save($path); $object->setData($this->getAttribute()->getName(), $result['file']); $this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName()); } catch (\Exception $e) { if ($e->getCode() != \Magento\MediaStorage\Model\File\Uploader::TMP_NAME_EMPTY) { $this->_logger->critical($e); } } return $this; }
/** * Save image * * @param string $fileId * @param string $destination * @return array * @throws LocalizedException */ protected function save($fileId, $destination) { $result = ['file' => '', 'size' => '']; /** @var Image $backendModel */ $backendModel = $this->getBackendModel($fileId); $uploader = $this->uploaderFactory->create(['fileId' => $fileId]); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(false); $uploader->setAllowedExtensions($backendModel->getAllowedExtensions()); $uploader->addValidateCallback('size', $backendModel, 'validateMaxSize'); return array_intersect_key($uploader->save($destination), $result); }
protected function setUp() { $this->_uploader = $this->getMock('Magento\\MediaStorage\\Model\\File\\Uploader', [], [], '', false); $this->_uploaderFactory = $this->getMock('Magento\\MediaStorage\\Model\\File\\UploaderFactory', ['create'], [], '', false); $this->_uploaderFactory->expects($this->any())->method('create')->will($this->returnValue($this->_uploader)); $this->_directoryMock = $this->getMock('Magento\\Framework\\Filesystem\\Directory\\Read', [], [], '', false); $this->_filesystemMock = $this->getMock('Magento\\Framework\\Filesystem', [], [], '', false); $this->_filesystemMock->expects($this->any())->method('getDirectoryRead')->will($this->returnValue($this->_directoryMock)); /** @var $service \Magento\Theme\Model\Uploader\Service */ $this->_fileSizeMock = $this->getMockBuilder('Magento\\Framework\\File\\Size')->setMethods(['getMaxFileSize'])->disableOriginalConstructor()->getMock(); $this->_fileSizeMock->expects($this->any())->method('getMaxFileSize')->will($this->returnValue(600 * self::MB_MULTIPLIER)); }
/** * @dataProvider dataForExecute */ public function testExecute($fileResult, $expectedResult) { $this->uploaderFactoryMock->expects($this->once())->method('create')->willReturn($this->uploaderMock); $this->adapterFactoryMock->expects($this->once())->method('create')->willReturn($this->adapterMock); $this->filesystemMock->expects($this->once())->method('getDirectoryRead')->with('media')->willReturn($this->mediaDirectoryMock); $this->uploaderMock->expects($this->once())->method('save')->willReturn($fileResult); $this->configMock->expects($this->once())->method('getTmpMediaUrl')->with($fileResult['file'])->willReturn('http://domain.com/tpm_dir/m/a/magento.png'); $this->swatchHelperMock->expects($this->once())->method('moveImageFromTmp')->with('/m/a/magento.png.tmp')->willReturn('/m/a/magento.png'); $this->swatchHelperMock->expects($this->once())->method('generateSwatchVariations'); $this->swatchHelperMock->expects($this->once())->method('getSwatchMediaUrl')->willReturn('http://domain.com/media/path/'); $this->responseMock->expects($this->once())->method('setBody')->willReturn(json_encode($expectedResult)); $this->controller->execute(); }
protected function setUp() { $this->contextMock = $this->getMockBuilder('Magento\\Framework\\Model\\Context')->disableOriginalConstructor()->getMock(); $this->registryMock = $this->getMockBuilder('Magento\\Framework\\Registry')->getMockForAbstractClass(); $this->scopeConfigMock = $this->getMockBuilder('Magento\\Framework\\App\\Config\\ScopeConfigInterface')->getMockForAbstractClass(); $this->typeListMock = $this->getMockBuilder('Magento\\Framework\\App\\Cache\\TypeListInterface')->getMockForAbstractClass(); $this->uploaderFactoryMock = $this->getMockBuilder('Magento\\MediaStorage\\Model\\File\\UploaderFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock(); $this->requestDataMock = $this->getMockBuilder('Magento\\Config\\Model\\Config\\Backend\\File\\RequestData\\RequestDataInterface')->getMockForAbstractClass(); $this->filesystemMock = $this->getMockBuilder('Magento\\Framework\\Filesystem')->disableOriginalConstructor()->getMock(); $this->writeMock = $this->getMockBuilder('Magento\\Framework\\Filesystem\\Directory\\WriteInterface')->getMock(); $this->uploaderMock = $this->getMockBuilder('Magento\\MediaStorage\\Model\\File\\Uploader')->disableOriginalConstructor()->getMock(); $this->uploaderFactoryMock->expects($this->any())->method('create')->willReturn($this->uploaderMock); $this->filesystemMock->expects($this->once())->method('getDirectoryWrite')->with(DirectoryList::MEDIA)->willReturn($this->writeMock); $this->model = new Logo($this->contextMock, $this->registryMock, $this->scopeConfigMock, $this->typeListMock, $this->uploaderFactoryMock, $this->requestDataMock, $this->filesystemMock); }
/** * Upload product image. * * @param $fileId * @return string */ public function uploadImage($fileId) { // Validate all of them first. if (!$this->isFileValid($fileId, true)) { return []; } /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */ $uploader = $this->_fileUploaderFactory->create(['fileId' => $fileId]); $uploader->setAllowedExtensions($this->_allowed_image_extensions); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(true); $path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('catalog/product/'); $uploader->save($path); $fullPath = $path . $uploader->getUploadedFileName(); return $fullPath; }
/** * Checking file for save and save it to tmp dir * * @param string $fileId * * @return string[] * * @throws \Magento\Framework\Exception\LocalizedException */ public function saveFileToTmpDir($fileId) { $baseTmpPath = $this->getBaseTmpPath(); $uploader = $this->uploaderFactory->create(['fileId' => $fileId]); $uploader->setAllowedExtensions($this->getAllowedExtensions()); $uploader->setAllowRenameFiles(true); $result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath)); if (!$result) { throw new \Magento\Framework\Exception\LocalizedException(__('File can not be saved to the destination folder.')); } /** * Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS */ $result['tmp_name'] = str_replace('\\', '/', $result['tmp_name']); $result['path'] = str_replace('\\', '/', $result['path']); $result['url'] = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . $this->getFilePath($baseTmpPath, $result['file']); $result['name'] = $result['file']; if (isset($result['file'])) { try { $relativePath = rtrim($baseTmpPath, '/') . '/' . ltrim($result['file'], '/'); $this->coreFileStorageDatabase->saveFile($relativePath); } catch (\Exception $e) { $this->logger->critical($e); throw new \Magento\Framework\Exception\LocalizedException(__('Something went wrong while saving the file(s).')); } } return $result; }
/** * @expectedException \Magento\Framework\Exception\LocalizedException * @expectedExceptionMessage Exception! */ public function testBeforeSaveWithException() { $value = 'value'; $groupId = 1; $field = 'field'; $tmpFileName = 'tmp_file_name'; $name = 'name'; $path = 'path'; $scope = 'scope'; $scopeId = 2; $uploadDir = 'upload_dir'; $fieldConfig = ['upload_dir' => $uploadDir]; $fileData = ['tmp_name' => $tmpFileName, 'name' => $name]; $exception = 'Exception!'; $this->model->setValue($value); $this->model->setPath($path); $this->model->setScope($scope); $this->model->setScopeId($scopeId); $this->model->setFieldConfig($fieldConfig); $_FILES['groups']['tmp_name'][$groupId]['fields'][$field]['value'] = $tmpFileName; $this->requestDataMock->expects($this->once())->method('getTmpName')->with($path)->willReturn($tmpFileName); $this->requestDataMock->expects($this->once())->method('getName')->with($path)->willReturn($name); $this->uploaderFactoryMock->expects($this->any())->method('create')->with(['fileId' => $fileData])->willReturn($this->uploaderMock); $this->uploaderMock->expects($this->once())->method('save')->with($uploadDir, null)->willThrowException(new \Exception($exception)); $this->model->beforeSave(); }
/** * Save new image and remove old image. * * @param $file string new file * @param $old string old file * * @return string file name * @throws LocalizedException */ public function saveImage($file, $old) { $uploadDir = $this->_mediaDirectory->getAbsolutePath(self::UPLOAD_POST_IMAGE_DIR); try { $uploader = $this->_uploaderFactory->create(['fileId' => $file]); $uploader->setAllowedExtensions(self::TYPES_ALLOWED); $uploader->setAllowRenameFiles(true); $uploader->addValidateCallback('size', $this, 'validateMaxSize'); $result = $uploader->save($uploadDir); } catch (\Exception $e) { throw new LocalizedException(__($e->getMessage())); } if ($old) { $this->removeImage($old); } return $result['file']; }
public function testSaveToTmp() { $path = 'design/header/logo_src'; $fieldCode = 'header_logo_src'; $metadata = [$fieldCode => ['path' => $path, 'backend_model' => 'Magento\\Theme\\Model\\Design\\Backend\\Image']]; $this->metadataProvider->expects($this->once())->method('get')->willReturn($metadata); $this->backendModelFactory->expects($this->once())->method('createByPath')->with($path)->willReturn($this->backendModel); $this->uploaderFactory->expects($this->once())->method('create')->with(['fileId' => $fieldCode])->willReturn($this->uploader); $this->uploader->expects($this->once())->method('setAllowRenameFiles')->with(true); $this->uploader->expects($this->once())->method('setFilesDispersion')->with(false); $this->backendModel->expects($this->once())->method('getAllowedExtensions')->willReturn(['png', 'jpg']); $this->uploader->expects($this->once())->method('setAllowedExtensions')->with(['png', 'jpg']); $this->uploader->expects($this->once())->method('addValidateCallback')->with('size', $this->backendModel, 'validateMaxSize'); $this->imageConfig->expects($this->once())->method('getAbsoluteTmpMediaPath')->willReturn('absolute/path/to/tmp/media'); $this->uploader->expects($this->once())->method('save')->with('absolute/path/to/tmp/media')->willReturn(['file' => 'file.jpg', 'size' => '234234']); $this->imageConfig->expects($this->once())->method('getTmpMediaUrl')->with('file.jpg')->willReturn('http://magento2.com/pub/media/tmp/file.jpg'); $this->assertEquals(['file' => 'file.jpg', 'size' => '234234', 'url' => 'http://magento2.com/pub/media/tmp/file.jpg'], $this->imageProcessor->saveToTmp($fieldCode)); }
public function testExecute() { $data = ['tmp_name' => 'tmp_name', 'path' => 'path', 'file' => 'file']; $uploader = $this->getMockBuilder('Magento\\MediaStorage\\Model\\File\\Uploader')->disableOriginalConstructor()->getMock(); $resultJson = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\Json')->disableOriginalConstructor()->setMethods(['setData'])->getMock(); $this->request->expects($this->once())->method('getParam')->with('type')->willReturn('samples'); $this->sample->expects($this->once())->method('getBaseTmpPath')->willReturn('base_tmp_path'); $this->uploaderFactory->expects($this->once())->method('create')->willReturn($uploader); $this->fileHelper->expects($this->once())->method('uploadFromTmp')->willReturn($data); $this->storageDatabase->expects($this->once())->method('saveFile'); $this->session->expects($this->once())->method('getName')->willReturn('Name'); $this->session->expects($this->once())->method('getSessionId')->willReturn('SessionId'); $this->session->expects($this->once())->method('getCookieLifetime')->willReturn('CookieLifetime'); $this->session->expects($this->once())->method('getCookiePath')->willReturn('CookiePath'); $this->session->expects($this->once())->method('getCookieDomain')->willReturn('CookieDomain'); $this->resultFactory->expects($this->once())->method('create')->willReturn($resultJson); $resultJson->expects($this->once())->method('setData')->willReturnSelf(); $this->assertEquals($resultJson, $this->upload->execute()); }
/** * upload file * * @param $input * @param $destinationFolder * @param $data * @return string * @throws \Magento\Framework\Exception\LocalizedException */ public function uploadFileAndGetName($input, $destinationFolder, $data) { try { if (isset($data[$input]['delete'])) { return ''; } else { $uploader = $this->uploaderFactory->create(['fileId' => $input]); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(true); $uploader->setAllowCreateFolders(true); $result = $uploader->save($destinationFolder); return $result['file']; } } catch (\Exception $e) { if ($e->getCode() != \Magento\Framework\File\Uploader::TMP_NAME_EMPTY) { throw new \Magento\Framework\Exception\LocalizedException($e->getMessage()); } else { if (isset($data[$input]['value'])) { return $data[$input]['value']; } } } return ''; }
/** * Upload image file * * @param string $key * @return array * @throws \Magento\Framework\Exception\LocalizedException */ public function uploadFile($key) { $result = []; /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */ $uploader = $this->_uploaderFactory->create(['fileId' => $key]); $uploader->setAllowedExtensions($this->_allowedExtensions); $uploader->setAllowRenameFiles(true); $uploader->setAllowCreateFolders(true); if (!$uploader->save($this->getStoragePath())) { /** @todo add translator */ throw new \Magento\Framework\Exception\LocalizedException(__('Cannot upload file.')); } $result['css_path'] = implode('/', ['..', self::PATH_PREFIX_QUICK_STYLE, $uploader->getUploadedFileName()]); $result['name'] = $uploader->getUploadedFileName(); return $result; }
/** * Move uploaded file and create source adapter instance. * * @throws \Magento\Framework\Exception\LocalizedException * @return string Source file path */ public function uploadSource() { /** @var $adapter \Zend_File_Transfer_Adapter_Http */ $adapter = $this->_httpFactory->create(); if (!$adapter->isValid(self::FIELD_NAME_SOURCE_FILE)) { $errors = $adapter->getErrors(); if ($errors[0] == \Zend_Validate_File_Upload::INI_SIZE) { $errorMessage = $this->_importExportData->getMaxUploadSizeMessage(); } else { $errorMessage = __('File was not uploaded.'); } throw new \Magento\Framework\Exception\LocalizedException($errorMessage); } $entity = $this->getEntity(); /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */ $uploader = $this->_uploaderFactory->create(['fileId' => self::FIELD_NAME_SOURCE_FILE]); $uploader->skipDbProcessing(true); $result = $uploader->save($this->getWorkingDir()); $extension = pathinfo($result['file'], PATHINFO_EXTENSION); $uploadedFile = $result['path'] . $result['file']; if (!$extension) { $this->_varDirectory->delete($uploadedFile); throw new \Magento\Framework\Exception\LocalizedException(__('Uploaded file has no extension')); } $sourceFile = $this->getWorkingDir() . $entity; $sourceFile .= '.' . $extension; $sourceFileRelative = $this->_varDirectory->getRelativePath($sourceFile); if (strtolower($uploadedFile) != strtolower($sourceFile)) { if ($this->_varDirectory->isExist($sourceFileRelative)) { $this->_varDirectory->delete($sourceFileRelative); } try { $this->_varDirectory->renameFile($this->_varDirectory->getRelativePath($uploadedFile), $sourceFileRelative); } catch (\Magento\Framework\Exception\FileSystemException $e) { throw new \Magento\Framework\Exception\LocalizedException(__('Source file moving failed')); } } $this->_removeBom($sourceFile); // trying to create source adapter for file and catch possible exception to be convinced in its adequacy try { $this->_getSourceAdapter($sourceFile); } catch (\Exception $e) { $this->_varDirectory->delete($sourceFileRelative); throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage())); } return $sourceFile; }
/** * Upload and resize new file * * @param string $targetPath Target directory * @param string $type Type of storage, e.g. image, media etc. * @return array File info Array * @throws \Magento\Framework\Exception\LocalizedException */ public function uploadFile($targetPath, $type = null) { /** @var \Magento\MediaStorage\Model\File\Uploader $uploader */ $uploader = $this->_uploaderFactory->create(['fileId' => 'image']); $allowed = $this->getAllowedExtensions($type); if ($allowed) { $uploader->setAllowedExtensions($allowed); } $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(false); $result = $uploader->save($targetPath); if (!$result) { throw new \Magento\Framework\Exception\LocalizedException(__('We can\'t upload the file right now.')); } // create thumbnail $this->resizeFile($targetPath . '/' . $uploader->getUploadedFileName(), true); $result['cookie'] = ['name' => $this->getSession()->getName(), 'value' => $this->getSession()->getSessionId(), 'lifetime' => $this->getSession()->getCookieLifetime(), 'path' => $this->getSession()->getCookiePath(), 'domain' => $this->getSession()->getCookieDomain()]; return $result; }