我试图上传图片并添加到db文件名,现在我卡住了,因为它不会向db添加条目。
调试器中的错误是属性"EeCarTypes.foto" is not defined.
控制器相关代码:
public function actionCreate()
{
$model=new EeCarTypes;
$path = Yii::app()->basePath . '/../images/upload/cartypes';
if (!is_dir($path)) {
mkdir($path);
}
if(isset($_POST['EeCarTypes']))
{
$model->attributes=$_POST['EeCarTypes'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save())
{
$model->image->saveAs( $path . '/adsfasdfadf' );
}
}
$this->render('create', array('model'=>$model));
}
查看代码:
$form = $this->beginWidget(
'CActiveForm',
array(
'id' => 'upload-form',
'enableAjaxValidation' => false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)
);
// ...
echo $form->labelEx($model, 'image');
echo $form->fileField($model, 'image');
echo $form->error($model, 'image');
// ...
echo CHtml::submitButton('Submit');
$this->endWidget();
和型号代码:
public $image;
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'ee_car_types';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array( 'image', 'file', 'types' => 'jpg, gif, png'),
array('car_type', 'length', 'max'=>255),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, car_type', 'safe', 'on'=>'search'),
);
}
我认为其他任何事情都在这里。请帮帮我:)。
答案 0 :(得分:2)
**Replace your view code**
echo $form->fileField($model, 'image');
with
<?php echo CHtml::activeFileField($model, 'image'); ?>
**In your controller file**
if(isset($_POST['EeCarTypes']))
{
$rnd = rand(0,9999);
$model->attributes=$_POST['EeCarTypes'];
$uploadedFile=CUploadedFile::getInstance($model,'image');
$fileName = "{$rnd}-{$uploadedFile}";
$model->image = $fileName;
$model->attributes=$_POST['EeCarTypes'];
if($model->save()){
$uploadedFile->saveAs(Yii::app()->basePath.'/../images/upload/cartypes'.$fileName);
$this->redirect(array('index'));
}
}
答案 1 :(得分:0)
在模型EeCarTypes中创建名为foto的属性并查看here
答案 2 :(得分:0)
在您的模型中,您应该为图像和数据库中的字段创建名称属性。然后在调用save()之前,使用action方法将文件名分配给此属性,如下所示:
$file = CUploadedFile::getInstance($model,'image');
$model->image_name = $file->name;
//use this if you want to save the file type but first create the image_type property
$model->image_type = $file->type;
[...]