页面
-------------------------------------------------
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'add-form',
'enableClientValidation'=>true,
'clientOptions'=>array( 'validateOnSubmit'=>true,),
'htmlOptions'=>array('enctype'=>'multipart/form-data'),
));
?>
<table>
<tr>
<td width="20%">
<b>ファイルパス:</b> <font color="red">*</font>
</td>
<td width="80%">
<?php echo CHtml::activeFileField($model, 'file'); ?>
<?php echo $form->error($model,'file');?>
</td>
</tr>
</table>
<table>
<tr>
<td>
<?php echo CHtml::button('上传', array('submit' => array('downfiles/upload'))); ?>
</td>
</tr>
</table>
Model
-------------------------------------------------
public function rules()
{
return array(
array('file', 'file','allowEmpty'=>true ,
'types'=>'jpg, gif, png, doc, txt',
'maxSize'=>1024 * 1024 * 10, // 10MB
'tooLarge'=>'The file was larger than 10MB. Please upload a smaller file.',
),
);
}
上传
-------------------------------------------------
public function actionUpload(){
$model = new DownFiles();
if(isset($_POST["DownFiles"])){
$model->attributes=$_POST['DownFiles'];
$file = CUploadedFile :: getInstance($model, 'file');
if(is_null($file)){
yii::app ()->user->setFlash('failed', '请选择上传文件');
$this->render('upload', array('model' => $model));
return ;
}
if (is_object($file) && get_class($file) == 'CUploadedFile') {
Yii::log("File Name : " . $file->getName() );
// 文件类型
$model->fileType = strtolower($file->getExtensionName());
// 存储文件名
$newFileName = date('YmdHis') . '_' . rand(1000, 9999) . '.' . $model->fileType;
// 服务器端存储路径
$newFilepath = Yii::app()->params['upload_folder'] . $newFileName;
// 上传文件名
$model->fileName = $file->getName();
// 文件类型 (application/x-msdownload、application/pdf、application/octet-stream)
$model->fileType = $file->getType();
// 文件大小
$model->fileSize = $file->getSize();
if ($model->validate() && $model->save()){
// 将文件存在在服务器端
$file->saveAs($newFilepath);
yii::app ()->user->setFlash('successed', '上传成功');
} else {
yii::app ()->user->setFlash('failed', '上传失败');
}
} else {
yii::app ()->user->setFlash('failed', '上传失败');
}
$this->render('upload', array('model' => $model));
}else{
$this->render('upload', array(
'model' => $model,
));
}
}
文件
-------------------------------------------------
public function actionDownload(){
if (isset($_GET["id"])) {
$id = $_GET["id"];
$model = DownFiles::model()->find('id =:id', array('id' => $id));
if ($model == null) {
throw new CHttpException ('500', '文件不存在');
} else {
// 服务器端文件的路径
$fileName = $model->saveFilePath ;
if (file_exists($fileName)){
yii::app ()->request->sendFile ($model->fileName, file_get_contents ($fileName));
}
}
}
}