Yii Framework 上传文件的方法 [ 技术分享 ]
First declare an attribute to store the file name in the model class (either a form model or an active record model). Also declare a file validation rule for this attribute to ensure a file is uploaded with specific extension name.
class Item extends CActiveRecord
{
public $image;
// ... other attributes
public function rules()
{
return array(
array('image', 'file', 'types'=>'jpg, gif, png'),
);
}
}
Then, in the controller class define an action method to render the form and collect user-submitted data.
class ItemController 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));
}
}
Finally, create the action view and generate a file upload field.
<?php
echo CHtml::form('','post',array('enctype'=>'multipart/form-data'));
?>
...
<?php
echo CHtml::activeFileField($model, 'image');
?>
...
<?php
echo CHtml::endForm();
?>
共 4 条回复
-
lqfmaxwell 回复于 2012-03-05 23:31 举报
试了一下这个方法,确实可行。
path/to/localFile 这个路径有点不清楚,比如我如何去获取原文件名?或者获取原文件的后缀名,这样我才好构造新的文件路径啊?求解 -
lqfmaxwell 回复于 2012-03-05 23:37 举报
补充一下上面那个问题,我现在获取原文件名,是用下面这个代码获取:
$sourceName = $_FILES['Item']['name']['image'];
╃巡洋艦㊣ 北京
注册时间:2010-11-21
最后登录:13小时前
在线时长:1676小时0分
最后登录:13小时前
在线时长:1676小时0分
- 粉丝1369
- 金钱76453
- 威望845
- 积分101663