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

前端 未结 15 2151
悲&欢浪女
悲&欢浪女 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 17:04

    For CDNs, you can also inject the Packages directly into your service.

    First the asset base url in config.yml:

    framework:
        assets:
            base_url:
                - 'http://cdn.mysite.com'
    

    Then the fun part:

    namespace App\Service;
    
    use Symfony\Component\Asset\Packages;
    
    class SomeClass
    {
        private $packages;
    
        public function __construct(Packages $packages)
        {
            $this->packages = $packages;
        }
    
        public function proxyToAssetUrl(string $path): string
        {
            return $this->packages->getUrl($path);
        }
    }
    

    If you have autowiring enabled then you won't need to configure anything in your services.yml, otherwise something like:

    services:
        App\Service\SomeClass:
            class: App\Service\SomeClass
            arguments: ['@assets.packages']
    

提交回复
热议问题