I have succeeded in uploading an image and saving it to the database. I generate a random string after saving the image in the database and in the images folder under web/uploads/images. I have failed to display the images on the web yet other images can show corrrectly. Any idea?
This is my controller
public function actionUploadPicture()
{
$model = $this->findModel(Yii::$app->user->id);
$model->scenario = ‘picture’;
if ($model->load(Yii::$app->request->post())) {
$image = UploadedFile::getInstance($model, 'image');
if (!is_null($image)) {
$model->image_src_filename = $image->name;
$file_extension = explode(".", $image->name);
$ext = end($file_extension);
// generate a unique file name to prevent duplicate filenames
$model->image_web_filename = Yii::$app->security->generateRandomString().".{$ext}";
// the path to save file, you can set an uploadPath
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/images/';
$path = Yii::$app->params['uploadPath'] . $model->image_web_filename;
$image->saveAs($path);
}
if ($model->save(false)) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
var_dump ($model->getErrors()); die();
}
}
return $this->render('signup', [
'model' => $model,
]);
}
And this is my view.
<h1><?= Html::encode($this->title) ?></h1>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'firstname',
'lastname',
'username',
'email',
'mobile_phone',
'user_level',
'created_at',
'updated_at',
'image_web_filename',
'image_src_filename',
],
]) ?>
<?php
if ($model->image_web_filename!='') {
echo Html::a(Html::img(Yii::getAlias('@web').'/uploads/images/'.$model->image_web_filename, ['alt'=>'somepic']));
}
?>