【问题标题】:How to force download for remote file in Symfony2?如何在 Symfony2 中强制下载远程文件?
【发布时间】:2015-02-24 17:10:38
【问题描述】:

我的控制器看起来像这样:

public function downloadAction($filename) {
    // Adding url to filename
    $path = $this->container->getParameter('remotepath').$filename;

    // Checking if file exists
    $ch = curl_init($path);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($code == 200) {
        // Get the file
        $file = file_get_contents($path);

        // Generate Response
        $response = new Response();

        $d = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);
        $response->headers->set('Content-Disposition', $d);

        $response->setContent($file);
    } else {
        $response = new Response();
        $response->setContent('File not found. ('.$filename.')');
        $response->headers->set('Content-Type', 'text/html');
        $response->setStatusCode(404);
    }
    return $response;
}

我想要完成的是获取一个远程文件(图像、pdf、...)并强制下载该文件。 但出于某种原因,Symfony 总是将标题和文件内容作为纯文本(-> 乱码)在浏览器中显示。

我找不到原因!

编辑: 我更改了代码,只创建了一个空的 Response() 并将其返回给控制器。在使用文件名调用 downloadAction 时,我将标题内容写入浏览器窗口。 所以我用 Firebug 检查了标题,看起来 Symfony 用正常的标题响应并打印了我为内容设置的标题。关于我做错了什么有什么建议吗?

【问题讨论】:

  • 你确定 file_get_contents 返回一个文件吗?由于您需要远程服务器的 PHP 将 allow_url_fopen 设置为 true 它可能会失败,所以我会先检查一下。您可能还想看看 StreamedResponse,这对于这种事情来说性能更好。
  • 查看手册 symfony.com/doc/current/components/http_foundation/… 他们有您可能感兴趣的 BinaryFileResponse。
  • 不幸的是,我正在开发不支持 BinaryFileResponse 的 Symfony 2.1。抱歉之前没有提到版本。在检查 StreamedResponse 时,我遇到了一个问题,我担心出现严重错误:我更改了代码,只创建了一个空的 Response() 并将其返回给控制器。在使用文件名调用 downloadAction 时,我将标题内容写入浏览器窗口。

标签: php symfony


【解决方案1】:

这可以通过 RedirectResponse 在您的控制器方法中执行以下操作来完成。

return new RedirectResponse($yourRemoteDownloadUrl);

在此示例中,$yourRemoteDownloadUrl 是一个 PDF 文件,位于 Amazon S3 存储桶中。

适用于 Symfony 2 和 3。

【讨论】:

  • 公平警告此解决方案不会“强制下载”(如问题中所问)配置为在浏览器中提供的文件类型。例如,我尝试了这种方法来强制下载 PNG 文件而不是提供它们,但它们只是显示在浏览器窗口中。
猜你喜欢
  • 1970-01-01
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多