I read a lot of article about the problem but it seems that there has to be no answer yet to this.
So my project directory is like :
+ uploads_dir
+ symfony_proj
- app
- bin
- src
- vendor
- web
I want to get the image inside the uploads_dir for me to use in my view page
I created twig extension that fetches the roor directory.. but it seems not to read if I put "root_dir"."../../uploads_dir".
Any suggestions ?
Here is the my twig extension part of it:
/**
* @var container
*/
protected $container;
public function __construct(ContainerInterface $container){
$this->container = $container;
}
public function bannerFilter($filename)
{
$file = $this->container->getParameter('kernel.root_dir').'../../uploads_dir'.$filename;
}
I would make the getting of a resource go through a function, this also enables your to do any kind of other checks (like is user logged in, etc).
Create a controller action that processes the request, and then in your twig you can just use a normal path()
function.
Some sample code; parameters.yml
parameters:
upload_destination: '%kernel.root_dir%/../../uploads_dir'
Sample function;
public function getFileAction($file_name)
{
$base_path = $this->container->getParameter('upload_destination');
$full_path = $base_path . '/' . $file_name;
$fs = new FileSystem();
if (!$fs->exists($full_path)) {
throw $this->createNotFoundException();
}
$file_name = basename($full_path);
$mime_type = $this->getMimeType($full_path);
$file = readfile($full_path);
$headers = array(
'Content-Type' => $mime_type,
'Content-Disposition' => 'inline; filename="'.$file_name.'"');
return new Response($file, 200, $headers);
}
protected function getMimeType($file)
{
if ('jpg' === substr($file, -3)) {
$best_guess = 'jpeg';
} else {
$guesser = MimeTypeGuesser::getInstance();
$best_guess = $guesser->guess($file);
}
return $best_guess;
}
In your twig;
<img src="{{ path('whatever_you_called_your_route', {'file_name': 'my_file.jpg'}) }}" />
I got passed this by using /uploads_dir/
. I hopes this helps.