Image 在yii 2.0中,图像保存在文件夹中,但未保存在数据库中

Image 在yii 2.0中,图像保存在文件夹中,但未保存在数据库中,image,file-upload,upload,yii2,image-upload,Image,File Upload,Upload,Yii2,Image Upload,我想上传图像到数据库,但图像只是存储在文件夹中,而不是保存在数据库中。我不明白是什么问题,请帮帮我,我是新来的。代码正在contoller上更新 php: <?php use yii\helpers\Html; use yii\widgets\ActiveForm; use kartik\file\FileInput; use backend\assets\DashboardAsset; /* @var $this yii\web\View */ /* @var $model app\

我想上传图像到数据库,但图像只是存储在文件夹中,而不是保存在数据库中。我不明白是什么问题,请帮帮我,我是新来的。代码正在contoller上更新

php:

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\file\FileInput;
use backend\assets\DashboardAsset;

/* @var $this yii\web\View */
/* @var $model app\models\User */
/* @var $form yii\widgets\ActiveForm */
DashboardAsset::register($this);
?>

<div class="user-form">

    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
    <div class='box box-widget'>
      <div class='box-header with-border'>
        <h1><?= $this->title;?></h1>
      </div>
      <div class='box-body'>

        <div class='row'>
          <div class='col-sm-7'>
            <div class='row'>
              <div class='col-sm-3 label-div'>
                First Name
              </div>
              <div class='col-sm-9'>
                <div class='row'>
                  <div class='col-sm-10'>
                    <?= $form->field($model, 'first_name')->textInput(['maxlength' => true])->label(false) ?>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class='row'>
          <div class='col-sm-7'>
            <div class='row'>
              <div class='col-sm-3 label-div'>
                Last Name
              </div>
              <div class='col-sm-9'>
                <div class='row'>
                  <div class='col-sm-10'>
                    <?= $form->field($model, 'last_name')->textInput(['maxlength' => true])->label(false) ?>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class='row'>
          <div class='col-sm-7'>
            <div class='row'>
              <div class='col-sm-3 label-div'>
                Avatar
              </div>
              <div class='col-sm-9'>
                <div class='row'>
                  <div class='col-sm-10'>
                    <?= $form->field($model, 'file')->FileInput() ?>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

      </div>
      <div class='box-footer'>
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
      </div>
    </div>

    <?php ActiveForm::end(); ?>

</div>

名字
姓
阿凡达
Controller.php:

<?php

namespace backend\controllers;

use Yii;
use app\models\User;
use backend\models\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new UserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new User();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            $path = "uploads/img/user/";
            $imageName = $model->username;
            //upload file
            $model->file = UploadedFile::getInstance($model, 'file');
            $model->file->saveAs($path.$imageName.'.'.$model->file->extension);
$model->avatar = $path.$imageName.'.'.$model->file->extension);

$model->save()

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

控制器在更新操作中也使用相同的代码

use yii\web\UploadedFile;
use backend\models\User;

public function actionCreate()
    {
        $model = new new User();

        if ($model->load(Yii::$app->request->post())){
                $model->file = UploadedFile::getInstances($model, 'file');
                if ($model->file) {
                    foreach ($model->file as $file) {
                        $path = 'uploads/images/' . $file->baseName . '.' . $file->extension;
                        $count = 0;
                        {
                            while(file_exists($path)) {
                               $path = 'uploads/images/' . $file->baseName . '_'.$count.'.' . $file->extension;
                               $count++;
                            }
                        }
                        $file->saveAs($path);
                        $files[] = $path;
                    } 
                      $model->file = implode(',', $files);
                     $model->save();
        return $this->redirect(['view', 'id' => $model->id]);}

         else{
         $model->file= $model->first_name;
         $model->save();
         return $this->redirect(['view', 'id' => $model->id]);
         }
            }
        else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
现在将以下内容添加到您的用户模型中(非强制性)


只需对您的代码执行上述操作,如果出现任何错误,请通知我,我们可以让它一起工作

首先从模型规则的必需部分删除
化身

第二行是
$model->file->saveAs($path.$imageName..'..$model->file->extension)
之后
$model->save()

第三,检查所有语法是否正确,因为我可以在
actionUpdate
中看到缺少一个分号

现在,新的
actionUpdate
如下所示:

  public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            $path = "uploads/img/user/";
            $imageName = $model->username;
            //upload file
            $model->file = UploadedFile::getInstance($model, 'file');

$model->avatar = $path.$imageName.'.'.$model->file->extension;

$model->save();

 $model->file->saveAs($model->avatar);

// or   $model->file->saveAs($path.$imageName.'.'.$model->file->extension);

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
public function rules()
    {
        return [
            [[ 'first_name', 'last_name'], 'required'],
            [['status', 'created_at', 'updated_at'], 'integer'],
            [['username','file', 'password_hash', 'password_reset_token', 'email', 'first_name', 'last_name', 'avatar'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
           //[['username'], 'unique'],
          //  [['email'], 'unique'],
            [['file'],'file'],
          //  [['password_reset_token'], 'unique'],
        ];
    }
最重要的一点是从所需的规则中删除表单不可见的所有其他列。否则数据将永远不会保存在数据库中

现在,您的模型规则如下所示:

  public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            $path = "uploads/img/user/";
            $imageName = $model->username;
            //upload file
            $model->file = UploadedFile::getInstance($model, 'file');

$model->avatar = $path.$imageName.'.'.$model->file->extension;

$model->save();

 $model->file->saveAs($model->avatar);

// or   $model->file->saveAs($path.$imageName.'.'.$model->file->extension);

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
public function rules()
    {
        return [
            [[ 'first_name', 'last_name'], 'required'],
            [['status', 'created_at', 'updated_at'], 'integer'],
            [['username','file', 'password_hash', 'password_reset_token', 'email', 'first_name', 'last_name', 'avatar'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
           //[['username'], 'unique'],
          //  [['email'], 'unique'],
            [['file'],'file'],
          //  [['password_reset_token'], 'unique'],
        ];
    }
还有一件事,将db中其他字段的默认值设置为
NULL

或者将所有其他字段添加到表单中,以便您也可以输入这些值。

将您的操作更新或操作创建带到您上传图像的位置。否则,如果需要,我将在我将图像保存到文件夹以及它到数据库中列的路径的位置共享我的代码table@SumithChalil很抱歉,有些代码尚未编写,我已经编辑了控制器,请回头看。哦,谢谢。。请将链接或电子邮件发送给我ixcmuhammadramadhan@gmail.comCan您还提供了模型的代码?@EdvinTenovimas我已经添加了模型,请回头看