Yii2.0 上传图片

Model

class Xxxx extends CActiveRecord
{
    public $image;
    // ... other attributes
 
    public function rules()
    {
        return array(
            array('image', 'file', 'types'=>'jpg, gif, png'),//验证上传文件类型
        );
    }
}

View

'multipart/form-data')); ?>
...

...

Controller

class XxxxController extends CController
{
    public function actionCreate()
    {
        $model=new Item;
        if(isset($_POST['Item']))
        {
            $model->attributes=$_POST['Item'];
            //这里保存图片名称到数据库
            $model->image=CUploadedFile::getInstance($model,'image');
            if($model->save())
            {
                $model->image->saveAs('path/to/localFile');//设置上传路径
                // redirect to success page
            }
        }
        $this->render('create', array('model'=>$model));
    }
}


你可能感兴趣的:(yii)