首先需要一個文件上傳的模型:FileUpload.php
?php class FileUpload extends CFormModel { public $image; /** * @return array validation rules for model attributes. */ public function rules() { return array( //note you wont need a safe rule here array('image', 'file', 'allowEmpty' => true, 'types' => 'jpg, jpeg, gif, png'), ); } }
注意:> 關於更多驗證規則的說明請查看 Reference: Model rules validation
下面來創建用於 CForm 的數組: uploadForm.php
<?php return array( 'title' => 'Upload your image', 'attributes' => array( 'enctype' => 'multipart/form-data', ), 'elements' => array( 'image' => array( 'type' => 'file', ), ), 'buttons' => array( 'reset' => array( 'type' => 'reset', 'label' => 'Reset', ), 'submit' => array( 'type' => 'submit', 'label' => 'Upload', ), ), );
創建視圖文件: upload.php
<?php if (Yii::app()->user->hasFlash('success')): ?> <div class="info"> <?php echo Yii::app()->user->getFlash('success'); ?> </div> <?php endif; ?> <h1>Image Upload</h1> <div class="form"> <?php echo $form; ?> </div>
添加控制器(controller)和動作(action):
<?php class FileUploadController extends CController { public function actionUpload() { $model = new FileUpload(); $form = new CForm('application.views.fileUpload.uploadForm', $model); if ($form->submitted('submit') && $form->validate()) { $form->model->image = CUploadedFile::getInstance($form->model, 'image'); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //do something with your image here //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Yii::app()->user->setFlash('success', 'File Uploaded'); $this->redirect(array('upload')); } $this->render('upload', array('form' => $form)); } }
在這裡最好的方式是在你的 FileUpload 模型中執行對圖片的一些操作。注意:你不需要向 FileUpload::image 賦值,但是可以提供訪問它的方法從而達到強壯模型(model)簡化控制器(controller).