【问题标题】:Symfony Routing QuestionSymfony 路由问题
【发布时间】:2011-05-20 01:50:42
【问题描述】:

我在 Linux 上运行 Symfony 1.4。我的应用程序创建 pdf 文件并将文件保存在以下目录中: /srv/www/vhosts/myapp/htdocs/stmts

以下是特定 pdf 文件的路径示例: /srv/www/vhosts/myapp/htdocs/stmts/example_001.pdf

我的 symfony 安装在以下路径: /srv/www/vhosts/myapp/htdocs

如何创建从我的 Symfony 应用程序到 example_001.pdf 文件的路由?我希望能够在我的 symfony 应用程序中创建指向 pdf 文件的链接。当用户单击该链接时,将打开 pdf。

谢谢

【问题讨论】:

    标签: php pdf routing symfony1


    【解决方案1】:

    为了使路由有意义,您需要执行以下操作:

    public function executeDownload(sfWebRequest $request)
    {
        // assume this method holds the logic for generating or getting a path to the pdf
        $pdfPath = $this->getOrCreatePdf();
    
        // disbale the layout
        $this->setLayout(false);
    
        $response = $this->getResponse();
    
        // return the binary pdf dat directly int he response as if serving a static pdf file
        $response->setHttpHeader('Content-Disposition', 'attachment; filename="'. basename($pdfPath));
        $response->setContentType('application/pdf');
        $response->setContent(file_get_contents($pdfPath));
    
        return sfView::NONE;
    }
    

    该操作实际上会读取文件并发送内容。但除非你有充分的理由这样做,否则不建议这样做,因为你会从 php 中招致不必要的开销。

    如果您确实有这样做的充分理由(限制访问、动态文件名等),那么您只需确定在该操作中需要使用哪些参数来确定文件系统上 pdf 的路径,然后设置正常路线。例如,假设您使用人类可识别的 slug 来引用文件。然后你有一个数据库记录,其中包含 slug 到文件路径的映射。在这种情况下,前面的操作可能如下所示:

    public function executeDownload(sfWebRequest $request)
    {
    
       $q = Doctrine_Core::getTable('PdfAsset')
         ->createQuery('p')
         ->where('slug = ?', $request->getSlug());
    
        $this->forward404Unless($asset = $q->fetchOne());
    
        $pdfPath = $asset->getPath();
    
        // disbale the layout
        $this->setLayout(false);
    
        $response = $this->getResponse();
    
        // return the binary pdf dat directly in the response as if serving a static pdf file
        $response->setHttpHeader('Content-Disposition', 'attachment; filename="'. basename($pdfPath));
        $response->setContentType('application/pdf');
        $response->setContent(file_get_contents($pdfPath));
    
        return sfView::NONE;
    }
    

    相应的路线看起来像:

    pdf_asset:
      url: /download/pdf/:slug
      params: {module: yourModule, action: 'download'}
    

    请注意,如果文件很大,您可能希望使用fopen 而不是file_get_contents,然后将数据作为流读取,这样您就不必将其全部放入内存中。这将要求您使用视图(但您仍将 layout 设置为 false 以防止布局包装您的流数据)。

    【讨论】:

    • 我认为我最初的问题不够清楚。该目录需要具有某种类型的安全性。理想情况下,我想使用 sfGuard 要求身份验证来读取此目录中的任何 pdf 文件。我只想对 pdf 文件使用 href 并将链接放在模板上。我不希望有人获得其中一个 pdf 文件的 url,然后无需身份验证即可读取该文件。
    • 查看我的其他 cmets... 在处理请求之前,您需要通过身份验证签入,就像使用任何其他安全操作(或使用 security.yml 配置它)一样。您不必使用我刚刚使用的数据库来说明这一点,因为它是一个典型的例子。
    猜你喜欢
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 2011-09-12
    • 2011-04-18
    • 1970-01-01
    相关资源
    最近更新 更多