How to get the full url for an asset in Controller?

前端 未结 15 2161
悲&欢浪女
悲&欢浪女 2020-12-12 16:13

I need to generate some JSON content in controller and I need to get the full URL to an uploaded image situated here : /web/uploads/myimage.jpg.

How can

15条回答
  •  难免孤独
    2020-12-12 16:57

    Working solution in Symfony 3.3+

    # app/config/config.yml
    parameters:
        ...
        base_url: 'http://mywebsite.com'
    

    To get it in your controller action:

    $baseUrl = $this->getParameter('base_url');
    

    You can now append your image to it e-g: $baseUrl . '/uploads/' . $image or if you like you can define uploaded assets base url in config.yml and access it in controller action.

    Best thing about this solution would be the ability to pre-define it for different environments e-g: in config.yml, config_dev.yml and config_test.yml so when you move your project between different environments, you don't have to change it as it's already there..

    Cheers!

提交回复
热议问题