如何在Yii2.0中通过POST API将文件上传到服务器?

Anw*_*rni 5 php yii2

我在yii2中通过此链接创建了一个模型 http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html 我使用POST请求将文件发布到API并在我的控制器中获取所有文件信息但是使用这个Yii2.0模型无法上传文件使用上面链接正常的PHP文件上传代码工作正常.这是我的控制器代码

public function actionUploadFile()
    {
        $upload = new UploadForm();
        var_dump($_FILES);

        $upload->imageFile = $_FILES['image']['tmp_name'];
        //$upload->imageFile = $_FILES;
        var_dump($upload->upload());
    }
Run Code Online (Sandbox Code Playgroud)

我的模型代码是

class UploadForm extends Model
    {
    /**
     * @var UploadedFile
     */
    public $imageFile;

    public function rules()
    {
        return [
            [['imageFile'], 'safe'],
            [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
        ];
    }

    public function upload()
    {
        try {
            if ($this->validate()) {
                $this->imageFile->saveAs('/var/www/html/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
                var_dump("Jeree");
                return true;
            } else {
                var_dump($this->getErrors());
                return false;
            }
        }catch (ErrorException $e) {
            var_dump($e->getMessage());
        }
    }
    }
Run Code Online (Sandbox Code Playgroud)

sca*_*dge 3

试试这个方法

public function actionUpload()
{
   $model = new UploadForm();

   if (Yii::$app->request->isPost) {
       $model->file = UploadedFile::getInstance($model, 'file');

       if ($model->validate()) {                
          $model->file->saveAs('/var/www/html/' . $model->file->baseName . '.' . $model->file->extension);
       }
    }

    return $this->render('upload', ['model' => $model]);
}
Run Code Online (Sandbox Code Playgroud)