【问题标题】:Serving files via symfony2 - path to uploads directory通过 symfony2 提供文件 - 上传目录的路径
【发布时间】:2015-07-08 18:38:16
【问题描述】:

我在设置 symfony2 上传目录的正确路径时遇到问题。

我正在尝试向用户提供他们之前上传的文件。

首先我尝试了以下代码:

$response = new Response();
        $d = $response->headers->makeDisposition(
         ResponseHeaderBag::DISPOSITION_ATTACHMENT,
         $document->getWebPath()
         );
         $response->headers->set('Content-Disposition', $d);

按照食谱和How to get web directory path from inside Entity? 中的建议。

然而,这导致了以下错误:

 The filename and the fallback cannot contain the "/" and "\" characters. 

因此我决定切换到:

     $filename = $this->get('kernel')->getRootDir() . '/../web' . $document->getWebPath();

     return new Response(file_get_contents($filename), 200, $headers);

然而这会导致:

Warning: file_get_contents(/***.pl/app/../web/uploads/documents/2.pdf) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: No such file or directory 

我要提供的文件位于

/web/uploads/documents/2.pdf

我应该使用什么代码将此文件提供给最终用户?

【问题讨论】:

    标签: symfony


    【解决方案1】:

    为了提供二进制文件,最好使用BinaryFileResponse,它接受绝对文件路径作为参数。 setContentDisposition() 不接受文件路径,但文件名......并且该参数是可选的(您应该只在您想要更改提供给最终用户的文件的名称时使用它):

    use Symfony\Component\HttpFoundation\BinaryFileResponse;
    
    $response = new BinaryFileResponse($filePath);
    $response->setContentDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT, $fileName
    ); // This line is optional to modify file name
    

    关于文件路径,你可以继续使用你展示的代码,但略有改变:

    $filePath = $this->container->getParameter('kernel.root_dir')
            .'/../web/'
            .$document->getWebPath();
    

    【讨论】:

      猜你喜欢
      • 2016-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      相关资源
      最近更新 更多