Yii2。 上传文件时出错

My Code related is the following:

Model Rules

[['documentTypeId', 'itemId', 'name', 'document'], 'required'],
            [['document'], 'file', 'skipOnEmpty' => false, 'extensions' => ['png', 'jpg', 'doc', 'pdf'], 'checkExtensionByMimeType'=>false],

Model method

public function upload($file)
    {
        if ($this->validate()) {
            $userFolder = Yii::getAlias("@app")."/uploads/".$this->item->userId;
            if(BaseFileHelper::createDirectory($userFolder) !== false) {
                $fileName = uniqid(rand(), false) . '.' . $this->document->extension;
                $file->saveAs($userFolder.'/' . $fileName);

                $this->document = $file->name;

                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }
    }

Controller

$model = new ItemDocument();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {

            $file = UploadedFile::getInstance($model, 'document');

            if($model->upload($file) !== false) {
                $model->save();
            }

            return $this->redirect(['view', 'id' => $model->id]);
        }



        return $this->render('create', [
            'model' => $model,
        ]);

This is giving me a validation error: "Document can not be blank". If I set "Document" field as not required and submit form I get "Please upload a file."

I am uploading this through a form with some other fields.

Any ideas?

I have found the error it was the model->validate() on controller. When i do:

$model->load(Yii::$app->request->post()) 

File content is not loaded to the "document" field. Yii generates a hidden field which is empty. So I need first to do this:

$file = UploadedFile::getInstance($model, 'document');

So now my controller looks like this:

$model = new ItemDocument();

        if ($model->load(Yii::$app->request->post())) {

            $model->document = UploadedFile::getInstance($model, 'document');

            if($model->validate()) {

                if ($model->upload() !== false) {
                    $model->save();
                }

                return $this->redirect(['view', 'id' => $model->id]);
            }
        }

        return $this->render('create', [
            'model' => $model,
        ]);

And I removed the validation inside upload method on model. Hope it helps someone.