public function actionUpload() { $response = ['success' => false]; Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $request = Yii::$app->getRequest(); $dir = \skeeks\sx\Dir::runtimeTmp(); $uploader = new \skeeks\widget\simpleajaxuploader\backend\FileUpload("imgfile"); $file = $dir->newFile()->setExtension($uploader->getExtension()); $originalName = $uploader->getFileName(); $uploader->newFileName = $file->getBaseName(); $result = $uploader->handleUpload($dir->getPath() . DIRECTORY_SEPARATOR); if (!$result) { $response["msg"] = $uploader->getErrorMsg(); return $result; } else { $storageFile = Yii::$app->storage->upload($file, array_merge(["name" => "", "original_name" => $originalName])); if ($request->get('modelData') && is_array($request->get('modelData'))) { $storageFile->setAttributes($request->get('modelData')); } $storageFile->save(false); $response["success"] = true; $response["file"] = $storageFile; return $response; } return $response; }
/** * @return CheckComponent[] */ public function loadChecksComponents() { $result = []; $dir = new Dir($this->basePath . "/" . static::CHECKS_DIR_NAME); if ($dir->isExist()) { if ($files = $dir->findFiles()) { foreach ($files as $file) { $className = $this->checkNamespace . "\\" . $file->getFileName(); if (class_exists($className)) { $component = new $className(); if (is_subclass_of($component, CheckComponent::className())) { $result[$component->className()] = $component; } } } } } return $result; }
public function actionUpload() { $response = ['success' => false]; Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $request = Yii::$app->getRequest(); $dir = \skeeks\sx\Dir::runtimeTmp(); $uploader = new \skeeks\widget\simpleajaxuploader\backend\FileUpload("imgfile"); $file = $dir->newFile()->setExtension($uploader->getExtension()); $originalName = $uploader->getFileName(); $uploader->newFileName = $file->getBaseName(); $result = $uploader->handleUpload($dir->getPath() . DIRECTORY_SEPARATOR); if (!$result) { $response["msg"] = $uploader->getErrorMsg(); return $result; } else { $storageFile = Yii::$app->storage->upload($file, array_merge(["name" => "", "original_name" => $originalName])); if ($request->get('modelData') && is_array($request->get('modelData'))) { $storageFile->setAttributes($request->get('modelData')); } $storageFile->save(false); if ($group = $request->get("group")) { /** * * @var \skeeks\cms\models\helpers\ModelFilesGroup $group */ $group = $model->getFilesGroups()->getComponent($group); if ($group) { try { $group->attachFile($storageFile)->save(); } catch (\yii\base\Exception $e) { $response["msgError"] = $e->getMessage(); } } } $response["success"] = true; $response["file"] = $storageFile; return $response; } return $response; }
/** * @return bool */ public function existsRootPath() { if (is_dir($this->rootBasePath)) { return true; } //Создать папку для файлов если ее нет $dir = new Dir($this->rootBasePath); if ($dir->make()) { return true; } return false; }
/** * * Загрузить файл в хранилище, добавить в базу, вернуть модель StorageFile * * @param UploadedFile|string|File $file объект UploadedFile или File или rootPath до файла локально или http:// путь к файлу (TODO:: доделать) * @param array $data данные для сохранения в базу * @param null $clusterId идентификатор кластера по умолчанию будет выбран первый из конфигурации * @return StorageFile * @throws Exception */ public function upload($file, $data = [], $clusterId = null) { //Для начала всегда загружаем файл во временную диррикторию $tmpdir = Dir::runtimeTmp(); $tmpfile = $tmpdir->newFile(); if ($file instanceof UploadedFile) { $extension = File::object($file->name)->getExtension(); $tmpfile->setExtension($extension); if (!$file->saveAs($tmpfile->getPath())) { throw new Exception("Файл не загружен во временную диррикторию"); } } else { if ($file instanceof File || is_string($file) && BaseUrl::isRelative($file)) { $file = File::object($file); $tmpfile->setExtension($file->getExtension()); $tmpfile = $file->move($tmpfile); } else { if (is_string($file) && !BaseUrl::isRelative($file)) { $curl_session = curl_init($file); if (!$curl_session) { throw new Exception("Неверная ссылка"); } curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_session, CURLOPT_BINARYTRANSFER, true); $file_content = curl_exec($curl_session); curl_close($curl_session); if (!$file_content) { throw new Exception("Не удалось скачать файл"); } $extension = pathinfo($file, PATHINFO_EXTENSION); $pos = strpos($extension, "?"); if ($pos === false) { } else { $extension = substr($extension, 0, $pos); } if ($extension) { $tmpfile->setExtension($extension); } $is_file_saved = file_put_contents($tmpfile, $file_content); if (!$is_file_saved) { throw new Exception("Не удалось сохранить файл"); } //Если в ссылке нет расширения if (!$extension) { $tmpfile = new File($tmpfile->getPath()); try { $mimeType = FileHelper::getMimeType($tmpfile->getPath(), null, false); } catch (InvalidConfigException $e) { throw new Exception("Не удалось пределить расширение файла: " . $e->getMessage()); } if (!$mimeType) { throw new Exception("Не удалось пределить расширение файла"); } $extensions = FileHelper::getExtensionsByMimeType($mimeType); if ($extensions) { if (in_array("jpg", $extensions)) { $extension = 'jpg'; } else { if (in_array("png", $extensions)) { $extension = 'png'; } else { $extension = $extensions[0]; } } $newFile = new File($tmpfile->getPath()); $newFile->setExtension($extension); $tmpfile = $tmpfile->copy($newFile); } } } else { throw new Exception("Файл должен быть определен как \\yii\\web\\UploadedFile или \\skeeks\\sx\\File или string"); } } } $data["type"] = $tmpfile->getType(); $data["mime_type"] = $tmpfile->getMimeType(); $data["size"] = $tmpfile->size()->getBytes(); $data["extension"] = $tmpfile->getExtension(); //Елси это изображение if ($tmpfile->getType() == 'image') { if (extension_loaded('gd')) { list($width, $height, $type, $attr) = getimagesize($tmpfile->toString()); $data["image_height"] = $height; $data["image_width"] = $width; } } if ($cluster = $this->getCluster($clusterId)) { if ($newFileSrc = $cluster->upload($tmpfile)) { $data = array_merge($data, ["src" => $cluster->getPublicSrc($newFileSrc), "cluster_id" => $cluster->getId(), "cluster_file" => $newFileSrc]); } } $file = new StorageFile($data); $file->save(false); return $file; }
/** * @return Dir */ public function getDir() { return Dir::object((string) $this->getDirName()); }
/** * Проверка папка пустая или нет * @param $dirPath */ protected function _checkIsEmptyDir($dirPath) { if ($dirPath instanceof Dir) { $dir = $dirPath; } else { $dir = new Dir($dirPath); } if ($dir->findFiles() || $dir->findDirs()) { $this->stdoutN('Папка assets (' . $dir->getPath() . ') не очищена. В ней остались файлы'); } else { $this->stdoutN('Папка assets (' . $dir->getPath() . ') очищена.'); } }
/** * @return array<Dir> */ public function findDirs() { $dir = $this->getPath(); $files = array(); if ($dir[strlen($dir) - 1] != '/') { $dir .= '/'; //добавляем слеш в конец если его нет } $nDir = opendir($dir); while (false !== ($file = readdir($nDir))) { if (!is_dir($dir . "/" . $file)) { continue; } if ($file != "." and $file != "..") { //если это не директория $files[] = Dir::object($dir . $file); } } closedir($nDir); return $files; }