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条)

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?