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
You can generate the url from the request object:
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
You could make a twig extension that cuts the /web
part of your path and uses the request to generate the base url.
see Symfony\Component\Routing\Generator\UrlGenerator::doGenerate
for a more solid implementation.
Also, Twig has access to the request from app.request
.
If you want to get this url from within a twig template use:
{{ app.request.uriForPath('/uploads/myimage.jpg') }}
The @Al Jey solution works fine with Assetic (tested on Symfony 2.6)
{% image '@AcmeBundle/Resources/public/images/myimage.jpg' %}
<img src="{{ app.request.uriForPath(asset_url) }}">
{% endimage %}
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!
As of Symfony 2.1 you can use:
$request->getSchemeAndHttpHost().'/uploads/myimage.jpg';
Note: This solution has the advantage to work in both DEV and PROD environments.
You can use this in Controller:
$this->getRequest()->getUriForPath('/uploads/myimage.jpg');
EDIT : This method also includes the app.php
and app_dev.php
to the url. Meaning this will only work in production when url-rewriting is enabled!