How to configure global uploadPath and uploadUrl in Yii2?

倾然丶 夕夏残阳落幕 提交于 2019-12-10 13:23:35

问题


I want to configure Global Params in Yii2.

For example this:

  1. This will store the server path for all your file uploads.

Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/uploads/';

  1. This will store the Url pointing to server location for your file uploads.

Yii::$app->params['uploadUrl'] = Yii::$app->urlManager->baseUrl . '/uploads/';

When I set params like this:

'uploadPath' => Yii::$app->basePath . '/uploads/',
'uploadUrl' => Yii::$app->urlManager->baseUrl . '/uploads/',

I am getting this error:

Notice: Trying to get property of non-object

I did this for uploadPath and its working:

'uploadPath' => Yii::getAlias('@common') . '/uploads/',

But I can't get the uploadUrl and print the image. Please help, how will I set global uploadUrl in params.


回答1:


Actually Application object Yii::$app does not exist at the moment of applying configuration. To be exact, it's created from that config and then will run.

So you can not set these params through config and should do this in other place, for example during application bootstrap.

To implement this with application boostrap:

1) Create custom class let's say called app\components\Bootstrap:

namespace app\components;

use yii\base\BootstrapInterface;

class Bootstrap implements BootstrapInterface
{
    public function bootstrap($app)
    {
        // Here you can refer to Application object through $app variable
        $app->params['uploadPath'] = $app->basePath . '/uploads/';
        $app->params['uploadUrl'] => $app->urlManager->baseUrl . '/uploads/';
    }     
}

2) Include it in boostrap section in application config:

'bootstrap' => [
    ...
    'app\components\Bootstrap',
];


来源:https://stackoverflow.com/questions/29345064/how-to-configure-global-uploadpath-and-uploadurl-in-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!