Warm tip: This article is reproduced from serverfault.com, please click

Yii2: display image in GridView Widget based on DB

发布于 2020-11-24 18:08:23

I have saved images in mysql db using this code

migration file

'content' => 'LONGBLOB NOT NULL',

controller file

$model->content = file_get_contents($model->path);

$model->save(false);
 

in view file and its works fine

echo '<img src="data:image/jpeg;base64,'.base64_encode($model->content).'"/>'; 

in gridview

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

            'attribute' => 'content',
            'format' => ['html'],
            'filter' => false,
            'value' => function ($data) {
                if (!empty($data['content'])) {
                    return Html::img(Yii::getAlias( $data['content'] )
                     ,['data:image/jpeg;base64'=>'.base64_encode']
                );
                }
                return "Not choosen";
            },
    
            ],
        ['class' => 'yii\grid\ActionColumn'],
    ],
    ]); 
?>

but there is nothing appearing

Questioner
Naeem Ali
Viewed
0
Rich Harding 2020-12-05 03:34:20

getAlias is for resolving a file path. You've read your image into the database. Your GridView code is trying to resolve a path, but from the image content you've read into the db, not from the original image on disk.

To display the saved image from the database, use:

Html::img('data:image/jpeg;base64,'.base64_encode($data->content),)