So I need to display images stored in backend/web/uploads to frontend views. I did some digging and found this post and example of asset publishing.
The recommended way to display an image from backend into frontend seems to be through asset publishing, but there are no full examples using images in the guide or in any of the posts.
I have no idea what I’m doing wrong, I’m not getting any error messages or even a broken image link.
Here is my code:
class ImageAsset extends AssetBundle
{
public $sourcePath = '@backend/web/';
public function init()
{
parent::init();
$this->publishOptions['beforeCopy'] = function ($from, $to) {
$dirname = basename(dirname($from));
return $dirname === 'uploads';
};
}
}
And to call in the view:
<?php
use yii\helpers\Html;
use frontend\assets\ImageAsset;
$bundle = ImageAsset::register($this);
echo Html::img($bundle->sourcePath.'/collation.jpg');
?>
In the above example, I have an image named collation.jpg that resides in backend/web/uploads. I want to display it from a view in the frontend. The ImageAsset class is located in frontend/assets.
'components' => [
//can name it whatever you want as it is custom
'urlManagerFrontend' => [
'class' => 'yii\web\urlManager',
'baseUrl' => 'myfrontend/absolutepath/uploads/',//i.e. $_SERVER['DOCUMENT_ROOT'] .'/yiiapp/web/'
'enablePrettyUrl' => true,
'showScriptName' => false,
],
],
In my frontend config i use
'components' => [
//can name it whatever you want as it is custom
'urlManagerBackend' => [
'class' => 'yii\web\urlManager',
'baseUrl' => 'mybackendend/absolutepath/uploads/',
'enablePrettyUrl' => true,
'showScriptName' => false,
],
],
since the subdomain is pointed to root/core/uploads you don’t put the folder name it in the url path.
It is also not accessable via browser url for two reasons:
static.mysite.com/uploads /somefile.pdf because that path really equals static.mysite.com/uploads /uploads /somefile.pdf due to the subdomain being pointed to that folder so that folder doesn’t exsist.
2.Most importantly request from mysite.com are the only request allowed to the subdomain.