I
I
Igor Lavrov2019-01-23 19:08:49
Yii
Igor Lavrov, 2019-01-23 19:08:49

How to solve multiload problem in Yii2?

Did according to Yii2 lessons for dummies.
Controller

public function actionSaveImg() 
    {
        $this->enableCsrfValidation = false;
        if (Yii::$app->request->isPost) {
            $post = Yii::$app->request->post();
            $dir = Yii::getAlias('@images').'/'.$post['ImageManager']['class'].'/';
            if(!file_exists($dir)){
                FileHelper::createDirectory($dir);
            }
            $result_link = str_replace('admin.','',Url::home(true)) . '/uploads/images/' . $post['class'] . '/';
            $file = UploadedFile::getInstanceByName('ImageManager[attachment]');
            $model = new ImageManager();
            $model->name = strtotime('now').'_'.Yii::$app->getSecurity()->generateRandomString(6) . '.' . $file->extension;
            $model->load($post);
            $model->validate();
            if ($model->hasErrors()) {
                $result = [
                    'error' => $model->getFirstError('file')
                ];
            } else {
                if ($file->saveAs($dir . $model->name)) {
                    $imag = Yii::$app->image->load($dir . $model->name);
                    $imag->resize(800, NULL, Yii\image\drivers\Image::PRECISE)
                        ->save($dir . $model->name, 85);
                    $result = ['filelink' => $result_link . $model->name, 'filename'=>$model->name];
                } else {
                    $result = [
                        'error' => 'ошибка'
                    ];
                }
                $model->save();
            }

            Yii::$app->response->format = Respose::FORMAT_JSON;

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

Model
class ImageManager extends \yii\db\ActiveRecord
{
    public $attachment;
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'image_manager';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['name', 'class', 'item_id'], 'required'],
            [['item_id'], 'integer'],
            [['name', 'class', 'alt'], 'string', 'max' => 150],
            [['attachment'], 'image'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'class' => 'Class',
            'item_id' => 'Item ID',
            'alt' => 'Alt',
        ];
    }
}

<?= \kartik\file\FileInput::widget([
    'name' => 'ImageManager[attachment]',
    'options'=>[
        'multiple'=>true
    ],
    'pluginOptions' => [
        'uploadUrl' => \yii\helpers\Url::to(['/site/save-img']),
        'uploadExtraData' => [
            'ImageManager[class]' => $model->formName(),
            'ImageManager[item_id]' => $model->id
        ],
        'maxFileCount' => 10
    ]
]); ?>

But still an error:
yii\base\ErrorException: Undefined index: class in /var/www/www-homepro/data/www//core/backend/controllers/SiteController.php:103
Stack trace:
#0 /var/www/www-homepro/data/www//core/backend/controllers/SiteController.php(103): yii\base\ErrorHandler->handleError(8, 'Undefined index...', '/var/www/www-ho...', 103, Array)
#1 [internal function]: backend\controllers\SiteController->actionSaveImg()
#2 /var/www/www-homepro/data/www//core/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#3 /var/www/www-homepro/data/www//core/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#4 /var/www/www-homepro/data/www//core/vendor/yiisoft/yii2/base/Module.php(528): yii\base\Controller->runAction('save-img', Array)
#5 /var/www/www-homepro/data/www//core/vendor/yiisoft/yii2/web/Application.php(103): yii\base\Module->runAction('site/save-img', Array)
#6 /var/www/www-homepro/data/www//core/vendor/yiisoft/yii2/base/Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#7 /var/www/www-homepro/data/www//admin/index.php(17): yii\base\Application->run()
#8 {main}

this line goes 103
$result_link = str_replace('admin.','',Url::home(true)) . '/uploads/images/' . $post['class'] . '/';

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Timofeev, 2019-01-23
@Maky_e0

Undefined index: class

means that there is no class index, as you can see from the code in the array $post, so the first thing to do is print this variable and understand what is in it. So far, it can be argued that it contains an array that definitely does not have an element with the index "class"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question