Yii2 -почему не загружаются картинки?

Различные вопросы по установке и настройке фреймворка, конфигурции веб-сервера и IDE.
Ответить
Radyar
Сообщения: 10
Зарегистрирован: 2017.07.19, 15:56

Yii2 -почему не загружаются картинки?

Сообщение Radyar »

При добавлении в блог картинки с помощью виджета imperavi она добавляется, но не сохраняется- т.е только в редакторе её видно (

Изображение
Изображение

Site.Controller.php

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

<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use yii\base\DynamicModel;
use vova07\imperavi\Widget;
use yii\base\Action;
use yii\base\InvalidConfigException;
use yii\helpers\FileHelper;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use yii\web\UploadedFile;
use yii\helpers\Url;
use yii\widgets\ActiveForm;


/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index','save-redactor-img'],
            
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }



public function actionSaveRedactorImg ($sub='main')
     
        {
        $this -> enableCsrfValidation = false;
        if (Yii::$app->request->isPost) {
        $dir = Yii::getAlias ('@images') .'/'.$sub.'/';
        if (!file_exists($dir)){
            FileHelper::createDirectory($dir);
        }


    $result_link = str_replace('admin.','',Url::home(true)).'/uploads/images/'.$sub.'/';
    $file = UploadedFile::getInstanceByName('file');
    $model = new DynamicModel (compact ('file'));
    $model ->addRule ('file', 'image')->validate();

        if ($model ->hasErrors()) {

            $result = [
            'error' => $model -> getFirstError ('file')
            ];
        } else {

            $model->file->name = strtotime('now').'_'.Yii::$app->getSecurity()->generateRandomString(6) . '.' . $model->file->extension;

           if ($model->file->saveAs ($dir . $model->file->name)) {
              $imag = Yii::$app->image->load($dir . $model->file->name);
                $imag -> resize (800, NULL, Yii\image\drivers\Image::PRECISE)
                ->save($dir . $model->file->name, 85); 
 
                $result = ['filelink' => $result_link . $model->file->name,'filename'=>$model->file->name];

        } else {

            $result = [
            'error' => Yii::t ('vova07/imperavi', 'ERROR_CAN_NOT_UPLOAD_FILE')
            ];

        }
    }
             Yii::$app->response->format = Response::FORMAT_JSON;

            return $result;
             } else {
                throw new BadRequestHttpException ('Only Post is allowed');
                    }
         }
     }

        
form.php

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

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use vova07\imperavi\Widget;
use yii\helpers\Url;
use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;


/* @var $this yii\web\View */
/* @var $model common\models\Blog */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="blog-form">

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'text')->widget(Widget::className(), [
    'settings' => [
        'lang' => 'ru',
        'minHeight' => 200,
        #'formatting' =>['p','blockquots', 'h2','h1'],
        'imageUpload' => \yii\helpers\Url::to(['/site/save-redactor-img','sub'=>'blog']),

        'plugins' => [
            'clips',
            'fullscreen'
        ]
    ]
])?>

    <?= $form->field($model, 'url')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'status_id')->dropDownList(\common\models\Blog::STATUS_LIST) ?>

    <?= $form->field($model, 'sort')->textInput() ?>

    <?= $form->field($model, 'tags_array')->widget(\kartik\select2\Select2::classname(), [
    'data' =>\yii\helpers\ArrayHelper::map(\common\models\Tag::find()->all(),'id','name'), 
    'language' => 'ru',
    'options' => ['placeholder' => 'Выбрать tag...','multiple'=>true],
    'pluginOptions' => [
        'allowClear' => true,
        'tags'=>true,
        'maximumInputLength'=> 10
    ],
]); ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>


urichalex
Сообщения: 994
Зарегистрирован: 2015.08.07, 11:03

Re: Yii2 -почему не загружаются картинки?

Сообщение urichalex »

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

'attributes' => [
    'text:html'
]
или

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

'attributes' => [
    [
    	'attribute' => 'text',
    	'format' => 'html'
    ]
]
Radyar
Сообщения: 10
Зарегистрирован: 2017.07.19, 15:56

Re: Yii2 -почему не загружаются картинки?

Сообщение Radyar »

Спасибо за ответ, ошибка исчезла но сейчас другая появилась..Пробую вариант загрузки с помощью виджета kartik-v/yii2-widget-fileinput. Виджет установился через composer. Но на страниче блога нет строки загрузки "Browse" - чтобы загружать картинки. В чем может быть проблема?

Blog.php

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

<?php

namespace common\models;

use common\components\behaviors\StatusBehavior;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Expression;
use yii\web\UploadedFile;
use yii\helpers\Url;
use kartik\widgets\FileInput;
use kartik\widgets\ActiveForm;


/**
 * This is the model class for table "blog".
 *
 * @property integer $id
 * @property string $title
 * @property string $image
 * @property string $text
 * @property string $date_create
 * @property string $date_update
 * @property string $url
 * @property integer $status_id
 * @property integer $sort
 */
   class Blog extends ActiveRecord {

  const STATUS_LIST = ['off','on'];
   /* public $tags_array;*/
   public $tags_array;
   public $file;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'blog';
    }


    public function behaviors()
    {
         return [
         'timestampBehavior'=>[
            'class' => TimestampBehavior::className(),
            'createdAtAttribute' => 'date_create',
            'updatedAtAttribute' => 'date_update',
            'value' => new Expression('NOW()'),
            ],
            'statusBehavior'=> [
            'class' => StatusBehavior::className(),
            'statusList'=> self::STATUS_LIST,
              ]
         ];
      }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'url'], 'required'],
            [['text'], 'string'],
            [['url'], 'unique'],
            [['status_id', 'sort'], 'integer'],
            [['sort'], 'integer','max'=>99, 'min'=>1],
            [['title', 'url'], 'string', 'max' => 150],
            [['image'], 'string', 'max' => 100],
            [['file'], 'image'],
            [['tags_array','date_create','date_update'],'safe'],

        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Заголовок',
            'text' => 'Текст',
            'url' => 'ЧПУ',
            'status_id' => 'Статус',
            'sort' => 'Сортировка',
            'date_update' => 'Обновлено',
            'date_create' => 'Создано',
            'tags_array' => 'Тэги',
            'tagsAsString' => 'Тэги',
            'image' => 'Картинка',
            'file' => 'Картинка',
            'author.username'=>'Имя Автора',
            'author.email'=>'Почта Автора',

        ];
    }

    public function getAuthor () {
      return $this->hasOne (User::className(),['id'=>'user_id']);
    
    }

     public function getBlogTag () {
      return $this->hasMany(BlogTag::className(),['blog_id'=>'id']);
    }

      public function getTags()
    {
      return $this->hasMany(Tag::className(),['id'=>'tag_id'])->via('blogTag');
    }

      public function getTagsAsString() 
    {  
       $arr = \yii\helpers\ArrayHelper::map($this->tags,'id','name');
       return implode (', ',$arr);
    }



 public function beforeSave ($insert)

{  
  if ($file = UploadedFile::getInstance($this,'file')) {
  $dir = Yii::getAlias ('@images').'/blog/';
 

             /*  if (!is_dir($dir . $this->image)) {*/
                if (file_exists($dir . $this->image)) {
                    unlink($dir . $this->image);
                }
                if (file_exists($dir . '50x50/' . $this->image)) {
                    unlink($dir . '50x50/' . $this->image);
                }
                if (file_exists($dir . '800x/' . $this->image)) {
                    unlink($dir . '800x/' . $this->image);
                }
            

    $this ->image = strtotime ('now').'_'.Yii::$app->getSecurity()->generateRandomString(6) .'.'. $file->extension;
    $file ->saveAs($dir.$this->image);
    $imag = Yii::$app->image->load($dir.$this->image);
    $imag ->background ('#fff',0);
    $imag ->resize ('50','50', Yii\image\drivers\Image::INVERSE);
    $imag ->crop ('50','50');
    $imag ->save($dir.'50x50/'.$this->image, 90);
    $imag = Yii::$app->image->load($dir.$this->image);
    $imag->background('#fff',0);
    $imag->resize('800',null, Yii\image\drivers\Image::INVERSE);
    $imag->save($dir.'800x/'.$this->image, 90);

    }
      return parent::beforeSave($insert);
  }





      public function afterFind() 
    {  

       parent::afterFind();

       $this->tags_array = $this->tags;
    }

      public function afterSave ($insert, $changedAttributes) 
    {
      parent::afterSave($insert, $changedAttributes);

      $arr = \yii\helpers\ArrayHelper::map($this->tags,'id','id');
      foreach ($this->tags_array as $one) {
       if(!in_array($one,$arr)){
          $model = new BlogTag();
          $model->blog_id = $this->id;
          $model->tag_id = $one;
          $model->save();
      }
      if(isset($arr[$one])) {
         unset ($arr[$one]);
      }
      }
       BlogTag::deleteAll(['tag_id'=>$arr]);
  }

   }





Bootstrap.php

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

<?php
Yii::setAlias('@common', dirname(__DIR__));
Yii::setAlias('@frontend', dirname(dirname(__DIR__)) . '/frontend');
Yii::setAlias('@backend', dirname(dirname(__DIR__)) . '/backend');
Yii::setAlias('@console', dirname(dirname(__DIR__)) . '/console');
Yii::setAlias('@images', dirname(dirname(dirname(__DIR__))) . '/public_html/uploads/images');
Ответить