【发布时间】:2015-08-22 07:03:46
【问题描述】:
我是 yii 和 php 的新手。 我想上传一个文件并将其路径保存到数据库,但这样做时出现错误。
我的控制器类是:
public function actionCreate()
{
$model = new Quiz();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$fileName = $model->name;
$model->file =UploadedFile::getInstance($model,'file');
$model->file->saveAs('uploadQuiz/'.$fileName.'.'.$model->file->extension );
$model->filePath = 'uploadQuiz/'.$fileName.'.'.$model->file->extension ;
$model->save();
return $this->redirect(['view', 'id' => $model->idQuiz]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
我保存文件路径的数据库列名称是“filePath”。 我的视图文件是:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Quiz */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="quiz-form">
<?php $form = ActiveForm::begin(['option' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'Course_idCourse')->textInput(['maxlength' => 100]) ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 100]) ?>
<?= $form->field($model, 'description')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'duration')->textInput(['maxlength' => 100]) ?>
<?= $form->field($model, 'time')->textInput() ?>
<?= $form->field($model, 'file')->fileInput(); ?>
<?= $form->field($model, 'totalMarks')->textInput(['maxlength' => 100]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
我的规则和属性是:
public function rules()
{
return [
[['Course_idCourse', 'duration', 'time'], 'required'],
[['Course_idCourse', 'duration', 'totalMarks'], 'integer'],
[['time'], 'safe'],
[['file'],'file'],
[['name', 'filePath'], 'string', 'max' => 200],
[['description'], 'string', 'max' => 255]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'idQuiz' => 'Id Quiz',
'Course_idCourse' => 'Course Id Course',
'name' => 'Name',
'description' => 'Description',
'duration' => 'Duration',
'time' => 'Time',
'file' => 'Quiz ',
'totalMarks' => 'Total Marks',
];
}
现在我已经参考了这个网站来解决同样的问题,但我发现它是为了 update 而不是 create 。请帮助我。 当我运行尝试创建时出现错误 在非对象上调用成员函数 saveAs() 我不知道我哪里出错了。
【问题讨论】:
-
$model->file 究竟是什么?请在 saveAs() 之前 var_dump
-
请同时提供创建视图(或_form)代码。我想在回答之前检查你从哪里得到文件名
-
@scaisEdge 我编辑了我的帖子,请查看。
-
@MuneebulHassan 请按照 Martin 的要求做,并包括
var_dump($model->file)的结果,就像在$model->file->saveAs(...之前一样 -
@topher ,我按照你说的做了,但错误是一样的。