R
R
Radiss2017-07-18 15:50:53
Yii
Radiss, 2017-07-18 15:50:53

Yii2 - why images are not loading?

Now the picture is added, but not saved - that is, it is visible only in the editor ( 0a7d755dc98242048c144faa7a743e1f.jpg54481b9e894c4a6ea491420cf0f2e599.jpg
SiteController.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>

index.php
<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\helpers\Url;
use yii\web\UploadedFile;
use vova07\imperavi\Widget;


/* @var $this yii\web\View */
/* @var $searchModel common\models\BlogSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Blogs';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="blog-index">

     
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Create Blog', ['create'], ['class' => 'btn btn-success']) ?>
    </p>
<?php Pjax::begin(); ?>  


 <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            [
                 'class' => 'yii\grid\ActionColumn',
                'template' => '{view} {update} {delete} {check}',
                'buttons' => [                
                    'check' => function($url,$model,$key) {
 return Html::a('<i class="fa fa-check" aria-hidden="true"></i>',$url);
                }
            ],
            'visibleButtons' => [
            'check' => function ($model, $key, $index){
              return $model->status_id === 1;
             }
        ]
],
            'id',
            'title',
            ['attribute'=>'url','format'=>'raw'],
            /*'headerOptions'=>['class'=>'dgfdhh']], */
          /*  ['attribute'=>'status_id','filter'=>['off','on'],'value'=>function($model){
                 $status = 'off';
                if($model->status_id ==1) {
                  $status = 'on';
         }
            return $status; 
 }], */

['attribute'=>'status_id','filter'=>\common\models\Blog::STATUS_LIST,'value'=>'statusName'],
    /* return $model->statusName;
 }],*/
     'sort',
     /*'date_create',*/
     'date_create:datetime',
     'date_update:datetime',
     ['attribute'=>'tags','value'=>'tagsAsString'],
         ],
           
     ]); ?>

<?php Pjax::end(); ?></div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2017-07-18
@webinar

adding pictures is a process consisting of many stages, so be specific about where exactly the problems occur.
As I understand it, you have an imperavi editor, it opens a dialog box, in which you select a photo, and then? Does ajax go to the server? What returns?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question