我想上传图片,我想将图像名称保存在数据库中并将图像移动到文件夹中..
但现在我无法保存任何东西。
上传文件并提交表单后,将显示以下错误
Error (#2)
An internal server error occurred.
我的代码在
之下在视图中:
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?php echo $form->field($model, 'varImage')->fileInput() ?>
<div class="form-group">
<?php echo Html::submitButton('Add', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
在模特中:
class Usertype extends \yii\db\ActiveRecord
{
public function rules()
{
return [
[['varImage'], 'safe'],
[['varImage'], 'file', 'extensions'=>'jpg, gif, png'],
];
}
public function attributeLabels()
{
return [
'varImage' => 'Image',
];
}
}
在控制器中:
$model = new Usertype();
if ($model->load(Yii::$app->request->post()) )
{
$image = UploadedFile::getInstance($model, 'varImage');
$path = Yii::$app->params['uploadPath'] . $model->varImage;
if($model->save())
{
$image->saveAs($path);
Yii::$app->getSession()->setFlash('error', 'User type inserted successfully');
return Yii::$app->getResponse()->redirect('/yii2/site/usertype');
}
}
我无法知道此代码中的错误
请帮我解决这个问题。
由于
答案 0 :(得分:0)
在控制器中:
$fileupload = UploadedFile::getInstance($model, 'image');
if(!empty($fileupload)){
$fileupload->saveAs('uploads/' . $fileupload->baseName . '.' . $fileupload->extension);
$model->image = $fileupload->baseName . '.' . $fileupload->extension;
$model->save();
}
观点:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'image')->fileInput()->label('Upload Photo') ?>
在模特中:
['image','safe']
答案 1 :(得分:0)
我认为你的视图和模型代码没问题。 试试这个。这是您的控制器代码。它对我有用。
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$image = UploadedFile::getInstance($model, 'varImage');
if(!empty($image)){
$image->saveAs('uploads/' . $image->baseName . '.' . $image->extension);
$model->your_database_field_name = $image->baseName . '.' . $image->extension;
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}