How to upload a file to server via POST API in Yii

2019-05-01 04:55发布

I make a model in yii2 from this link http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html I post the file using POST request to API and got all file information in my controller but unable to upload file using this Yii2.0 model created using above link normal PHP file upload code work fine. Here is my controller code

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

        $upload->imageFile = $_FILES['image']['tmp_name'];
        //$upload->imageFile = $_FILES;
        var_dump($upload->upload());
    }

and my model code is

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());
        }
    }
    }

标签: php yii2
1条回答
时光不老,我们不散
2楼-- · 2019-05-01 05:18

Try this way

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]);
}
查看更多
登录 后发表回答