/** * 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; }
/** * 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); }
/** * 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)); } }
/** * 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; }
/** * 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); }
/** * 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; }
/** * 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; }
/** * 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']; }
/** * 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; }