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

时间:2015-10-14 07:32:22

标签: php yii2

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

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

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

我的型号代码是

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

1 个答案:

答案 0 :(得分: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]);
}