Yii框架--file提交

1.表单文件(本例是_form.php,表单提交页面)
<?php $form=$this->beginWidget(‘CActiveForm’, array( ‘id’=>’product-form’, ‘htmlOptions’=>array(‘enctype’=>’multipart/form-data’), 
‘enableAjaxValidation’=>false,)); ?>//指定文件上传表单,enctype属性一定是要设置的
<div>  <?php echo $form->labelEx($model,’filename’); ?>                                                         <?php echo $form->FileField($model,’
filename’); ?>                                                                <?php echo $form->error($model,’filename’); ?> </div>//显示浏览文件
2.控制器动作(action)
$model=new Product;                                                                                                                      

if(isset($_POST['Product']))

{$model->attributes=$_POST['Product'];

$file=CUploadedFile::getInstance($model,’filename’); //获取表单名为filename的上传信息 
$filename=$file->getName();          //获取文件名                                                                         

$filesize=$file->getSize();//获取文件大小

$filetype=$file->getType();//获取文件类型

$model->filename=$filename;//数据库中要存放文件名

$filename1=iconv(“utf-8″,“gb2312″,$filename);//这里是处理中文的问题,非中文不需要

$uploadfile=”./assets/upload/”.$filename1;

$file->saveAs($uploadfile,true);//上传操作

if($model->save())//执行保存,写入数据库

$this->redirect(array(‘view’,'id’=>$model->id));}//数据存放成功,跳转到view页面

$category=Category::model()->findAll();//此处是为提交表单,传递分类信息

$this->render(‘create’,array( ‘model‘=>$model, ‘category’=>$category, )); }//交创建视图,并传递相应的信息,一是model,表单,二是category,分类信息
3.create.php(动作视图文件)
<?php echo $this->renderPartial(‘_form’, array(‘model’=>$model,‘category’=>$category)); ?>
4.view.php(页面显示)
<?php $this->widget(‘zii.widgets.CDetailView’, array( ‘data’=>$model, ‘attributes’=>array( ‘id’, ‘name’, ‘category_id’, ‘description’, array(
‘label’=>’filename’, ‘type’=>’raw’, ‘value’=>CHtml::link(CHtml::encode($model->filename),                                
“./assets/upload/”.CHtml::encode($model->filename)), ) ),)); ?>

yii

相关推荐