Yii2:如何使用保存在数据库中的图像路径在视图中显示图像


Yii2: How to display Image in View using image path saved in database?

尝试在视图中显示图像:

id_image 在 db 中保存图像路径。通过使用路径需要显示图像。尝试使用以下代码,但它没有显示任何图像。

<div class="row">
  <div class="col-xs-6 col-md-3">
    <a href="#" class="thumbnail">
      <img src="<?php $dataProvider->models[0]->id_image; ?>">
    </a>
  </div>

视图:

public function actionView($id)
    {
         $searchModel = new CreateBookingsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('view', [
            'model' => $this->findModel($id),
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

在控制器中创建/上传文件

public function actionCreate()
    {
        $model = new CreateBookings();
        if ($model->load(Yii::$app->request->post()))
        {
            $imageName = $model->first_name;
            $mobile = $model->primary_mobile;
            $model->file = UploadedFile::getInstance($model, 'file');
            $model->file->saveAs( 'uploads/id_images/'.$imageName.'_'.$mobile.'.'.$model->file->extension);
            //save the path in the db column
            $model->id_image = 'uploads/id_images/'.$imageName.'_'.$mobile.'.'.$model->file->extension;
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

保存在数据库中的路径示例:

uploads/id_images/kumar_9015879992.jpg

您必须将基本网址添加到图像路径中。使用下面的一个。

  <img src="<?php echo Yii::getAlias('@web').'/'.$dataProvider->models[0]->id_image; ?>">
我想在

将名称保存到DB之前first_name您想使用它,请尝试一下

if ($model->load(Yii::$app->request->post()))
{
    $model->save();
    //then use first_name on your image like you did.
    $model->save();
}