Jane08
Jane08

Reputation: 127

Yii2-advanced, how to display images from backend in frontend

I have my images in /backend/web/uploads. Now I would like to show them in /frontend/views/site/index

So in index view I'm trying to show them like this:

 $planet = Planet::find()->all();
foreach($planet AS $pl=> $p){
    echo Html::img('/backend/web/'.($p->path));
}   

in $p->path - uploads/123.jpg

But this path is not valid, how can I display images from /backend/web/uploads in /frontend/views/site/index ?

Upvotes: 0

Views: 5221

Answers (3)

Илья Шах
Илья Шах

Reputation: 117

I did it by creating of ONE directory for backend images and frontend images:

In my common/config/bootstrap.php:

Yii::setAlias('@root', dirname(dirname(__DIR__)));

In my common/config/main.php:

'modules' => [
      'yii2images' => [
         'class' => 'rico\yii2images\Module',
         //be sure, that permissions ok
         //if you cant avoid permission errors you have to create "images" folder in web root manually and set 777 permissions
         'imagesStorePath' => '@root/upload/store', //path to origin images
         'imagesCachePath' => '@root/upload/cache', //path to resized copies
         'graphicsLibrary' => 'GD', //but really its better to use 'Imagick'
         'placeHolderPath' => '@root/upload/store/no-image.png', // if you want to get placeholder when image not exists, string will be processed by Yii::getAlias
         'imageCompressionQuality' => 85, // Optional. Default value is 85.
      ],
]

And created the 'imagesStorePath' and the 'imagesCachePath' in the root project directory.

Upvotes: 0

ynroot
ynroot

Reputation: 79

Go to your frontend/config and add:

'components' => [
    // You can name it whatever you want as it is custom
    'urlManagerBackend' => [
        'class' => 'yii\web\urlManager',
        'baseUrl' => 'yourbackendend/absolutepath/uploads/',
        'enablePrettyUrl' => true,
        'showScriptName' => false,
    ],
],

Then you can use it like this:

Html::img(Yii::$app->urlManagerBackend->baseUrl.'/uploads/your_img.png');

Upvotes: 0

arogachev
arogachev

Reputation: 33548

It's already answered here.

There are two main options to achieve that.

1) You can create alias from frontend/web/images to backend/web/images to display images in backend from frontend.

Run ln -s ../../frontend/web/images images from backend/web folder. It's better to delete destination folder (backend/web/images) before doing that.

2) Alternative way to publish images from such directory will be creating asset bundle for that folder, that way images will be copied in frontend/web/assets for example. You can read more about asset bundles in official docs.

Upvotes: 3

Related Questions