dp610807 2016-02-18 08:57
浏览 106
已采纳

Symfony 2.7访问web目录外的图像

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;

    }
  • 写回答

2条回答 默认 最新

  • douzhanrun0497 2016-02-18 09:21
    关注

    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'}) }}" />
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致