Commit 79d7fcd7 authored by Shakarim Sapa's avatar Shakarim Sapa

- Добавлено сохранение переданного файла в файловой системе, и указание пути к нему в базе

parent 32be3feb
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
namespace common\modules\analyticsSchool\models; namespace common\modules\analyticsSchool\models;
use Yii; use Yii;
use yii\web\UploadedFile;
/** /**
* This is the model class for table "analytics_school_lesson_file". * This is the model class for table "analytics_school_lesson_file".
...@@ -11,12 +12,15 @@ use Yii; ...@@ -11,12 +12,15 @@ use Yii;
* @property integer $lesson_id * @property integer $lesson_id
* @property string $title * @property string $title
* @property string $file * @property string $file
* @property UploadedFile $document
* *
* @property AnalyticsSchoolLesson $lesson * @property AnalyticsSchoolLesson $lesson
*/ */
class AnalyticsSchoolLessonFile extends \yii\db\ActiveRecord class AnalyticsSchoolLessonFile extends \yii\db\ActiveRecord
{ {
public $document; public $document;
protected $save_folder = ['uploads', 'lessons'];
/** /**
* @inheritdoc * @inheritdoc
*/ */
...@@ -25,6 +29,37 @@ class AnalyticsSchoolLessonFile extends \yii\db\ActiveRecord ...@@ -25,6 +29,37 @@ class AnalyticsSchoolLessonFile extends \yii\db\ActiveRecord
return 'analytics_school_lesson_file'; return 'analytics_school_lesson_file';
} }
public function beforeSave($insert){
if (!parent::beforeSave($insert))
return false;
// Сгенерировали имя папки
$dirname = Yii::$app->security->generateRandomString(5);
// Определили mime тип файла и занесли его в массив
$fileFormat = explode('/', $this->document->type);
// Сгенерировали новое имя для файла
$fileName = Yii::$app->security->generateRandomString(5).'.'.$fileFormat[1];
// Определили папку в которую будет загружен файл
$saveDir = $this->getPath().DIRECTORY_SEPARATOR.$dirname;
// Если папка не найдена
if (!is_dir($saveDir))
// Создаем ее (рекурсивно)
mkdir($saveDir, 0777, true);
// Если до этого момента действие не было остановлено - сохраняем файл в файловой системе
if ($this->document->saveAs($saveDir.DIRECTORY_SEPARATOR.$fileName)) {
// Переопределяем значение в поле
$this->file = $this->getPath(false, '/').'/'.$dirname.'/'.$fileName;
}
return true;
}
public function getPath($absolute=true, $delimiter=DIRECTORY_SEPARATOR) {
$path = $delimiter.(implode($delimiter, $this->save_folder));
return ($absolute===true) ? Yii::getAlias('@frontend').$delimiter.'web'.$path : $path;
}
/** /**
* @inheritdoc * @inheritdoc
*/ */
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment