4

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

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. 

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

型号:MyFile.php

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

控制器: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();

 ?>
4

3 回答 3

6

CFormModel没有名为 的方法save(),如果要调用它,则必须实现它,但是在您的情况下您想要的是使用该validate方法

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

您可以通过调用验证上传的图像是 gif、png 或 jpg validate()

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));
        }
    }
}
于 2013-11-04T16:01:40.280 回答
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));
}
于 2014-03-25T08:10:36.663 回答
0
   $img = CUploadedFile::getInstance($model,'file');
        $randomNAme = hash('sha512',$model->file);

        $path = Yii::app()->basePath.'/'.'uploads/'.$img;
        $img->saveAs($path);
于 2016-07-13T05:24:19.337 回答