gpt4 book ai didi

php - Yii 使用模型上传文件

转载 作者:可可西里 更新时间:2023-10-31 22:43:57 24 4
gpt4 key购买 nike

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

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'),
);
}
}

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();

?>

最佳答案

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

如果 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));
}
}
}

关于php - Yii 使用模型上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19771372/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com