Menu Close

Yii1.1使用CUploadFile上传图片

Yii上传图片,使用CUploadedFile,参考如下.

CUploadedFile | Class Reference | Yii PHP Framework
http://www.yiiframework.com/doc/api/1.1/CUploadedFile

在视图可以使用Yii提供的FORM组件,也可以有原生file,只要是可以将文件信息转发到
后端.将文件信息转发到后端时,会带有如下信息

array(1) {

["input1453346446017"]=>
array(5) {

["name"]=>
string(16) "25b1OOOPIC19.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(14) "/tmp/phpL6APy7"
["error"]=>
int(0)
["size"]=>
int(97369)

}
}

最重要的信息是 tmp_name 信息.

到后端后,可以通过CUploadFile来操作图片文件,

Call getInstance to retrieve the instance of an uploaded file, and then use saveAs to save it on the server. You may also query other information about the file, including name__, __tempName__, __type__, __size and __error.

可以使用getInstance::getInstance(CModel $model, string $attribute)来获取文件的实例(instance),然后save()到服务器,或者是第三方云存储这种做法是结合模型,因为我的业务上面 上传图片可能是多张,所以需要换其他方式.

可以使用__public static CUploadedFile getInstanceByName__($name)来获取一个实例,name是上传的文件字段名(the name of the file input field),

      //获取一个实例
      $instance = CUploadedFile::getInstanceByName(key($_FILES));
        //存放路径
        $dir =Yii::getPathOfAlias('wwwroot').'/upload/image/'.date('Ymd').'/';
        //不存在则创建
        if (!is_dir($dir)) {
            mkdir($dir); //目录不存在则创建
        }
        $filename = date('YmdHis').$instance->name;
        //文件名绝对路径
        $name = $dir.$filename;
        //保存
        $status = $instance->saveAs($name,true); //保存文件
        var_dump($status);

可以自己加一下验证,比如验证格式是否正确 大小是否正确等等.

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注