Yii使用CForm类(Form builder)上传文件

jerry Yii 2015年11月23日 收藏

模型(model)

首先需要一个文件上传的模型: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 的数组

下面来创建用于 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',
        ),
    ),
);

视图文件(view)

创建视图文件: 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)

添加控制器(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).