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

前端 未结 15 2092
悲&欢浪女
悲&欢浪女 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:05
    app.request.uriForPath('/uploads/myimage.jpg') | replace({'/app_dev.php': ''})
    

    this avoid the problem of app_dev.php

    0 讨论(0)
  • 2020-12-12 17:09

    You can use the function getSchemeAndHttpHost() for Gets the scheme and HTTP host and use the function getBasePath() to get the root path from which this request is executed

    $request->getSchemeAndHttpHost().$request->getBasePath()."/uploads/myimage.jpg"
    

    This method works fine for the app.php and app_dev.php.

    0 讨论(0)
  • You can get site url i.e point to web folder by using the following code

    $protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';

        $hostName = $request->server->get('HTTP_HOST');
    
        $baseDirectory = "";
    
        if(!empty($this->container->get('router')->getContext()->getBaseUrl())){
    
            $baseDirectory = str_replace('app_dev.php', '', $this->container->get('router')->getContext()->getBaseUrl());
        }
    
        $rootUrl = $protocol.$hostName.$baseDirectory;
    
    0 讨论(0)
提交回复
热议问题