/** * Загружает файл или изоображение * * Результаты загрузки записываются в массив _result и могут быть получены на странице загрузки с помощью метода * getResult() модели. * */ public function upload() { // Цикл по файлам, выбранным для загрузки foreach ($this->files as $file) { // Если файл - изображение if (getimagesize($file->tempName) !== false) { if ($imageFileName = $this->uploadImage($file)) { // Сохраняем в таблице images $image = new Images(); $image->image_name = $imageFileName; $image->folder = $this->folder; $image->post_id = $this->post_id; $image->user_id = $this->user_id; if (!$this->post_id) { $image->r_id = Yii::$app->request->cookies->getValue('r_id'); } $image->date = time(); // Сохраняем в базу. Если не удалось, пытаемся удалить изображения с диска if ($image->save()) { $this->_result[] = 'Изображение <strong>' . $file->name . '</strong> загружено'; } else { $this->_result[] = 'Не удалось сохранить изображение <strong>' . $file->name . '</strong> в базе данных'; $this->_result[] = $image->getErrors(); @unlink(Yii::getAlias('@frontend/web/uploads/') . $this->folder . '/' . $imageFileName); @unlink(Yii::getAlias('@frontend/web/uploads/') . $this->folder . '/thumbs/' . $imageFileName); } } } else { if ($fileName = $this->uploadFile($file)) { // Сохраняем в таблице images $uFile = new Files(); $uFile->name = $fileName; $uFile->folder = $this->_filesFolder; $uFile->post_id = $this->post_id; $uFile->user_id = $this->user_id; $uFile->size = filesize(Yii::getAlias($this->_baseUploadPathAlias) . $this->_filesFolder . '/' . $fileName); if (!$this->post_id) { $uFile->r_id = Yii::$app->request->cookies->getValue('r_id'); } // Сохраняем в базу. Если не удалось, пытаемся удалить файл с диска if ($uFile->save()) { $this->_result[] = 'Файл <strong>' . $file->name . '</strong> загружен'; } else { $this->_result[] = 'Не удалось сохранить файл <strong>' . $file->name . '</strong> в базе данных'; $this->_result[] = $uFile->getErrors(); @unlink(Yii::getAlias('@frontend/web/uploads/') . $this->_filesFolder . '/' . $fileName); } } } } }
/** * Creates a new Post model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Post(); if ($model->load(Yii::$app->request->post()) && $model->save()) { // Привязка загруженных файлов к id статьи $post_id = $model->id; Images::updateAll(['post_id' => $post_id, 'r_id' => null], ['r_id' => Yii::$app->request->cookies->getValue('r_id')]); Files::updateAll(['post_id' => $post_id, 'r_id' => null], ['r_id' => Yii::$app->request->cookies->getValue('r_id')]); return $this->redirect(['view', 'id' => $model->id]); } else { $model->loadDefaultValues(); if ($model->isNewRecord) { $model->date = (new \DateTime('now', new \DateTimeZone('Europe/Moscow')))->format('Y-m-d H:i:s'); $model->author_id = Yii::$app->user->getId(); } return $this->render('create', ['model' => $model]); } }
/** * Отображает форму загрузки файлов и список загруженных для статьи файлов * @return string */ public function actionIndex() { /*$post_id = Yii::$app->request->get('post_id'); var_dump($post_id); var_dump(Yii::$app->request->cookies->getValue('r_id'));*/ $model = new UploadForm(); if ($model->load(Yii::$app->request->post())) { $model->files = UploadedFile::getInstances($model, 'files'); if ($model->validate()) { $model->upload(); } } else { $model->create_thumb = Yii::$app->params['admin']['images']['create_thumb'] ? 1 : 0; $model->watermark = Yii::$app->params['admin']['images']['watermark'] ? 1 : 0; $model->max_pixel_side = Yii::$app->params['admin']['images']['max_pixel_side']; } $fModel = new DeleteFilesForm(); if ($fModel->load(Yii::$app->request->post()) && $fModel->validate()) { $fModel->delete(); } $q = Images::find(); if ($post_id = Yii::$app->request->get('post_id')) { $q->andWhere(['post_id' => $post_id]); } else { $q->andWhere(['r_id' => Yii::$app->request->get('r_id')]); } $images = $q->all(); $q = Files::find(); if ($post_id) { $q->andWhere(['post_id' => $post_id]); } else { $q->andWhere(['r_id' => Yii::$app->request->get('r_id')]); } $files = $q->all(); return $this->render('index', ['model' => $model, 'fModel' => $fModel, 'images' => $images, 'files' => $files]); }