Загрузка файлов и картинок в статьях

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
Sandro
Сообщения: 10
Зарегистрирован: 2017.11.09, 15:03

Загрузка файлов и картинок в статьях

Сообщение Sandro »

Здравствуйте!

Пытаюсь разобраться с загрузкой виджетов fileinput и imperavi. Arcticle controller находиться в папке vendor в dir D:\sites\yii2com\vendor\wokster\yii2-article\controllers
Загружаться файлы с картинками должны в dir D:\sites\yii2com\backend\web\uploads\images\articles

Вначале возникла ошибка: 'move_uploaded_file(): The second argument to copy() function cannot be a directory'

В файле UploadedFiles (D:\sites\yii2com\vendor\yiisoft\yii2\web)
вместо:

Код: Выделить всё

  public function saveAs($file, $deleteTempFile = true)
    {
       /* if ($this->error == UPLOAD_ERR_OK) {
            if ($deleteTempFile) {
                return move_uploaded_file($this->tempName, $file);
            } elseif (is_uploaded_file($this->tempName)) {
                return copy($this->tempName, $file);
            }
             return false;
    }
        }
было заменено:

Код: Выделить всё

	 public function saveAs($file, $deleteTempFile = true)
  if (isset($_FILES['file']['tmp_name']) and $_FILES['file']['type'] == "text/plain") {
    $filename = "текстовое_файло";
    if (@copy($_FILES['file']['tmp_name'],"./uploads/".$filename.".txt")) {
        unset($_FILES['file']);
        echo "все в порядке";
        }
    else echo "нет прав на запись в каталог";
    }
}
Появилась ошибка:
'There is no error, the file uploaded with success. Error code is 0'
http://joxi.ru/bmogRYQTM1vgJm
http://joxi.ru/D2PLgeRTdEzg02

В debug $_GET = [
'id' => '1',
];

$_POST = [
'_csrf-backend' => 'xBbA9S8mw8_iTGJbkQPVtZpbvwFNOb9PSan7_M5Iak6FRJPCAnOA9pUgLjbIMrnZ1Q7YdAJb3AYn0IySuS8PeA==',
'Article' => [
'fileUpload' => '',
'title' => 'article1',
'url' => '1',
'status_id' => '1',
'type_id' => '0',
'date_start' => '',
'date_finish' => '',
'new_tags' => '',
'seo_title' => 'art',
'seo_keywords' => 'art',
'seo_description' => 'art',
],
'date_start-article-date_start-disp' => '',
'date_finish-article-date_finish-disp' => '',
];

$_FILES = [
'Article' => [
'name' => [
'fileUpload' => 'chertogi-slavyan-avtor-1.jpg',
'file' => 'cspca9PT6jc.jpg',
],
'type' => [
'fileUpload' => 'image/jpeg',
'file' => 'image/jpeg',
],
'tmp_name' => [
'fileUpload' => 'W:\\userdata\\temp\\phpD4C2.tmp',
'file' => 'W:\\userdata\\temp\\phpD4C3.tmp',
],
'error' => [
'fileUpload' => 0,
'file' => 0,
],
'size' => [
'fileUpload' => 95755,
'file' => 137382,
],
],
];

ArcticleController

Код: Выделить всё

<?php

namespace wokster\article\controllers;
        

use yii;
use common\models\ImageManager;
use wokster\article\models\Article;
use wokster\article\models\ArticleSearch;
use yii\web\Controller;
use yii\web\MethodNotAllowedHttpException;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yiidreamteam\upload\FileUploadBehavior;
use vova07\imperavi\Widget;

/**
 * ArticleController implements the CRUD actions for Article model.
 */
class ArticleController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                    'delete-image' => ['POST'],
                    'sort-image' => ['POST'],

                ],
            ],
        ];
    }

    /**
     * Lists all Article models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ArticleSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Article model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Article model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new \wokster\arcticle\models\Arcticle();
        $model->sort = 50;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Article model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Article model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
   

  
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }



    public function actionDeleteImage()
    {
        if(($model = ImageManager::findOne(Yii::$app->request->post('key'))) and $model->delete()){
            return true;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionSortImage($id)
    {
        if(Yii::$app->request->isAjax){
            $post = Yii::$app->request->post('sort');
            if($post['oldIndex'] > $post['newIndex']){
                $param = ['and',['>=','sort',$post['newIndex']],['<','sort',$post['oldIndex']]];
                $counter = 1;
            }else{
                $param = ['and',['<=','sort',$post['newIndex']],['>','sort',$post['oldIndex']]];
                $counter = -1;
            }
            ImageManager::updateAllCounters(['sort' => $counter], [
               'and',['class'=>'article','item_id'=>$id],$param
               ]);
    
            ImageManager::updateAll(['sort' => $post['newIndex']], [
                    'id' => $post['stack'][$post['newIndex']]['key']
                ]);
                return true;
            }
            throw new MethodNotAllowedHttpException();
        }

        
          /**
     * Finds the Article model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Article the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
      protected function findModel($id)
    {
        if (($model = Article::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

    
Ответить