yii使用CUploadedFile上传文件的一般方法(二)
作者:zccst
与前面(http://zccst.iteye.com/blog/1114948)的区别是不再依赖model。
也不再依赖yii自带的前端表单控件activeFileField。
感觉这样轻量级多了。
简言之:
1,form要带enctype="multipart/form-data"
2,文件控件只需写name即可。<input type="file" name="fileName" />
3,直接在php端使用$attach = CUploadedFile::getInstanceByName("fileName");即可。
不需要先用$fileName = $this->request->getParam('fileName');
注可以在前端写多个相同name的文件控件,这样在后端用$attaches = CUploadedFile::getInstancesByName("fileName");即可
一、前端代码
二、后端代码public function actionRepairUpload(){ $attach = CUploadedFile::getInstanceByName('repair_attached_file'); $retValue = ""; if($attach->size > 3*1024*1024){ $retValue = "提示:文件大小不能超过3M"; }else{ $f = file_get_contents($attach->tempName); $a = new Attachment(); $a->ref_type = "failParts"; $a->data = $f; $a->file_path = $attach->name; $a->save(); $retValue = $a->id; } echo $retValue;}
关于CUploadedFile类的使用
通过 CUploadedFile::getInstance($model,'album_image');
或 $attach = CUploadedFile::getInstanceByName($inputFileName);
获取的对象$attach对象,有以下几个属性:
name
size
type
tempName
error
extensionName
hasError
常用方法有:
getName()
getSize()
getType()
getTempName()
getInstance()
getInstanceByName()
getInstances()
getInstancesByName()
saveAs()
reset() Cleans up the loaded CUploadedFile instances.