YII中文件上传

文件上传

1、视图文件代码

<?php

$form = $this->beginWidget("CActiveForm",array(

"action"=>__APP__."/index.php/admin/addnews/add",

"method"=>"post",

"htmlOptions"=>array(

"enctype"=>"multipart/form-data",

"style"=>"margin-top:20px;"

)

));

?>

<table border="1">

<tr>

<td height="30">&nbsp;新闻图片:</td>

<td><?php echo $form->fileField($newsModel,"imagepath",array("size"=>30))?></td>

</tr>

</table>

<?php $this->endWidget()?>

2、控制器文件代码

/*

CUploadedFile类的相关属性

name:文件名

tempName:临时存储目录

type:文件类型

size:文件大小

error:是否出错

CUploadedFile类的相关方法

$myFile->saveAs("完整保存路径");//保存上传文件

$myFile->getName();//获得上传文件名

$myFile->getTempName();//获得上传文件临时存储目录

$myFile->getType();//获得上传文件类型

$myFile->getSize();//获得上传文件大小

$myFile->getError();//获得上传文件是否出错

$myFile->getExtensionName();//获得上传文件扩展名

*/

$myFile = CUploadedFile::getInstance($newsModel,"imagepath");//获得上传文件信息,$myFile是一个对象存储着上传文件的相关信息

if($myFile != NULL)

{

$ext = $myFile->getExtensionName();//获得上传文件扩展名

$savePath = "newspicture/".md5(uniqid()).".".$ext;//获得保存路径

if($myFile->saveAs($savePath))//上传文件

{

echo "上传成功";

}

else

{

echo "上传失败";

}

}

else

{

echo "没有上传的文件";

}

posted @ 2016-04-14 18:26  郑彦彬  阅读(706)  评论(0编辑  收藏  举报