我是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,
]);
}
}
Run Code Online (Sandbox Code Playgroud)
我保存文件路径的数据库列名是"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>
Run Code Online (Sandbox Code Playgroud)
我的规则和属性是:
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',
];
}
Run Code Online (Sandbox Code Playgroud)
现在我已经将这个网站引用到同一个问题,但我发现它不是为了更新而是为了创建.亲切地帮助我.当我运行尝试创建我得到一个错误 调用一个成员函数saveAs()在一个非对象 我不知道我在哪里出错.
没有文件正在上传。option初始化时的参数应该ActiveForm是options
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3381 次 |
| 最近记录: |