Yii使用模型上传文件

时间:2013-11-04 15:42:58

标签: php yii

我只是尝试使用模型上传文件。我在当前情况下得到异常消息(参见下面的模型/控制器/视图):

CException
MyFile and its behaviors do not have a method or closure named "save". 

如果我的模型扩展了CActiveRecord而不是CFormModel,则会出现另一个异常:

CDbException
The table "MyFile" for active record class "MyFile" cannot be found in the database. 

我的错误是什么?这些是文件:

MODEL:MyFile.php

class MyFile extends CFormModel {
    public $image;
    public function rules () {
        return array (
            array ('image', 'file', 'types' => 'gif, jpg, png'),
        );
    }
}

CONTROLLER:MyFileController.php

class MyFileController extends CController {
    public function actionCreate() {
        $model = new MyFile;

        if(isset($_POST['MyFile'])) {

            $model->attributes=$_POST['MyFile'];
            $model->image=CUploadedFile::getInstance($model,'image');
            if($model->save()) {
                $path = Yii::app()->runtimePath.'/temp/uploadDirectory/'.$model->image;
                $model->image->saveAs($path);
            }
        }
        $this->render('create', array('model'=>$model));
    }
}

查看:create.php

 <h1>File-Upload</h1>

 <?php

    echo CHtml::form('','post',array('enctype'=>'multipart/form-data'));
    echo CHtml::activeFileField($model, 'image');
    echo CHtml::submitButton('abschicken', array('name' => 'submit'));
    echo CHtml::endForm();

 ?>

3 个答案:

答案 0 :(得分:6)

CFormModel没有名为save()的方法,如果你想调用它,你必须实现它,但你想要的是使用validate方法

如果MyFile没有相关的数据库表,那么它不应该扩展CActiveRecord

您可以致电validate()验证上传的图片是gif,png还是jpg:

class MyFileController extends CController {
    public function actionCreate() {
        $model = new MyFile;

        if(isset($_POST['MyFile'])) {

            $model->attributes=$_POST['MyFile'];
            $model->image=CUploadedFile::getInstance($model,'image');
            if($model->validate()) {
                //The image is valid, you can save it
                $path = Yii::app()->runtimePath.'/temp/uploadDirectory/'.$model->image;
                $model->image->saveAs($path);
            }
            $this->render('create', array('model'=>$model));
        }
    }
}

答案 1 :(得分:0)

  public function actionCreate() {
    $model = new Item;
    if (isset($_POST['Item'])) {
        $model->attributes = $_POST['Item'];
        $model->images = CUploadedFile::getInstance($model, 'images');
        if ($model->save()) {
            $path = Yii::app()->basePath . '/../uploads/' . $model->images;
            $model->images->saveAs($path);
            // redirect to success page
        }
    }
    $this->render('upload', array('model' => $model));
}

答案 2 :(得分:0)

   $img = CUploadedFile::getInstance($model,'file');
        $randomNAme = hash('sha512',$model->file);

        $path = Yii::app()->basePath.'/'.'uploads/'.$img;
        $img->saveAs($path);