Symfony 2.7 在 Web 目录之外访问图像


Symfony 2.7 access image outside web directory

我读了很多关于这个问题的文章,但似乎还没有答案。

So my project directory is like :
+ uploads_dir
+ symfony_proj
    - app
    - bin
    - src
    - vendor
    - web

我想获取uploads_dir内的图像,以便在我的视图页面中使用

我创建了获取roor目录的twig扩展..但是如果我输入"root_dir",它似乎无法读取。/../uploads_dir"。

有什么建议吗?

这是我的树枝扩展部分:

/**
     * @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;
    }

我会通过一个函数来获取资源,这也使您能够进行任何类型的其他检查(例如用户是否登录等)。
创建一个处理请求的控制器操作,然后在树枝中您可以使用正常的path()函数。
一些示例代码;参数.yml

parameters:
    upload_destination: '%kernel.root_dir%/../../uploads_dir'

示例函数;

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;
}

在你的树枝上;

<img src="{{ path('whatever_you_called_your_route', {'file_name': 'my_file.jpg'}) }}" />

我通过使用/uploads_dir/传递了这个。我希望这有所帮助。