How to configure global uploadPath and uploadUrl in Yii2?

I want to configure Global Params in Yii2.

For instance:

  • This will save the server path for all file downloads.

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

  1. This will save a URL indicating the location of the server for downloading files.

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

When I set options like this:

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

I get this error:

Note: attempt to get a non-object property

I did this for uploadPath and its work:

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

But I can not upload uploadUrl file and print the image. Help how to set global uploadUrl in parameters.

+6
source share
1 answer

In fact, the application object Yii::$app does not exist at the time the configuration is applied. More precisely, it is created from this config and will then work.

Therefore, you cannot set these parameters through the configuration and do it in another place, for example, during application loading.

To implement this using boostrap application:

1) Create your own class, for example, 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 the boostrap section in the application configuration:

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

Source: https://habr.com/ru/post/984432/


All Articles