Moldovan Andrei
Moldovan Andrei

Reputation: 315

Yii2 uploaded image doesn't display

So I've set a CRUD to upload a file to the server's root, in a folder called 'uploads'. Now, the file is properly saved in the particular folder and the database entry appears to be alright - but the images don't display in the CRUD's 'index' and 'view' actions. Any thoughts on this one?

Create:

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

        if ($model->load(Yii::$app->request->post())) {

            $model->image = UploadedFile::getInstance($model, 'image');

            if (Yii::$app->ImageUploadComponent->upload($model)) {
                Yii::$app->session->setFlash('success', 'Image uploaded. Category added.');

                return $this->redirect(['view', 'id' => $model->id]);
            } else {
                Yii::$app->session->setFlash('error', 'Proccess could not be successfully completed.');

                return $this->render('create', [
                    'model' => $model
                ]);
            }

        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

ImageUploadComponent file:

<?php 

namespace app\components;

use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;

class ImageUploadComponent extends Component {

    public function upload($model) {

        if ($model->image) {

            $imageBasePath = dirname(Yii::$app->basePath, 1) . '\uploads\\';
            $imageData = 'img' . $model->image->baseName . '.' . $model->image->extension;

            $time = time();

            $model->image->saveAs($imageBasePath . $time . $imageData);

            $model->image = $imageBasePath . $time . $imageData;

            if ($model->save(false)) {
                return true;
            } else {
                return false;
            }

        }

    }

}

And the index file for the views:

<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\modules\admin\models\PhotoGalleryCategoriesSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Photo Gallery Categories';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="photo-gallery-categories-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Create Photo Gallery Categories', ['create'], ['class' => 'btn btn-success']) ?>
    </p>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'name',

            'image' => [
                'attribute' => 'image',
                'value' => 'image',
                'format' => ['image', ['class' => 'col-md-6']]
            ],

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
</div>

enter image description here

Edit: In the dev tools, I can see the correct source for the image. What's more, I can access it by copy-pasting the address in the browser. (the first rows are images taken from the internet through their address, they are not saved locally.)

Upvotes: 0

Views: 1847

Answers (2)

Moldovan Andrei
Moldovan Andrei

Reputation: 315

I found this anomaly: while inspecting the image sources, I found out that Yii prepended the baseUrl to the image source, even though it displayed only the correct bit. So I manually assigned the path that goes into the database - this way the images show properly.

This is the upload function after the changes. To test it for the whole backend, I made it a component, and it works flawlessly.

    public function upload($model) {

        /**
        * If the $model->image field is not empty, proceed to uploading.
        */
        if ($model->image) {

            /**
            * Assign current time.
            */
            $time = time();

            /**
            * Create the basePath for the image to be uploaded at @root/uploads.
            * Create the image name.
            * Create the database model.
            */
            $imageBasePath = dirname(Yii::$app->basePath, 1) . '\uploads\\';
            $imageData = 'img' . $model->image->baseName . '.' . $model->image->extension;
            $imageDatabaseEntryPath = '../../../uploads/';

            $modelImageDatabaseEntry = $imageDatabaseEntryPath . $time . $imageData;

            $model->image->saveAs($imageBasePath . $time . $imageData);

            $model->image = $modelImageDatabaseEntry;

            /**
            * If the model can be saved into the database, return true; else return false.
            * Further handling will be done in the controller.
            */
            if ($model->save(false)) {
                return true;
            } else {
                return false;
            }

        }

    }

}

Upvotes: 0

amir ajlo
amir ajlo

Reputation: 124

if image upload in folder

you check below code in gridview with own path:

[
                'attribute' => 'image',
                'format' => 'html',
                'value' => function($data) {
                    if (empty($data['image'])) {
                        $img = 'default.jpg';
                    } else {
                        $img = $data['image'];
                    }


                    if (file_exists(\Yii::$app->basePath . \Yii::$app->params['path']['product'] . $img)) {
                        if (file_exists(\Yii::$app->basePath . \Yii::$app->params['path']['product'] . "t-" . $img)) {
                            $path = \Yii::$app->params['path']['webproduct'] . "t-" . $img;
                        } else {
                            $path = \Yii::$app->params['path']['webproduct'] . $img;
                        }
                    } else {
                        if (file_exists(\Yii::$app->basePath . \Yii::$app->params['path']['product'] . "t-default.jpg")) {
                            $path = \Yii::$app->params['path']['webproduct'] . "t-default.jpg";
                        } else {
                            $path = \Yii::$app->params['path']['webproduct'] . "default.jpg";
                        }
                    }

                    return Html::img($path, ['width' => '100px', 'height' => '100px']);
                },
                    ],

in params.php

\Yii::$app->params['path']['webproduct']:

 'product' => '/web/uploads/product/',
        'webproduct' => '/uploads/product/',

notice: i use basic template.

Upvotes: 0

Related Questions