【问题标题】:symfony - download filessymfony - 下载文件
【发布时间】:2016-09-20 20:16:34
【问题描述】:

我正在尝试在控制器中下载文件,但在控制台中我只看到一堆奇怪的字符而不是下载框。我正在关注这个话题Symfony2 - Force file download

不知道发生了什么...试图找到最简单的解决方案。 这是我的代码:

 $response = new Response(file_get_contents($file->realPath), 200, array(
            'Content-Type' => $file->mimeType,
            'Content-Length' => filesize($file->realPath),
            'Content-Disposition' => 'attachment; filename=' . $file->name,
        ));
 $response->send();

我什至尝试使用带有 header() 和 readfile() 的最基本示例。 我的服务器需要特殊配置吗?干杯。

【问题讨论】:

    标签: php symfony header download


    【解决方案1】:

    您可以使用 Symfony 的内置BinaryFileResponse,而不是重建这种响应。

    use Symfony\Component\HttpFoundation\BinaryFileResponse;
    
    $response = new BinaryFileResponse($file);
    

    请查看documentation about serving files

    【讨论】:

      【解决方案2】:

      在控制器中你可以使用$this->file(...)

      文件需要完整的文件系统路径和要下载的文件

      return $this->file('/home/website/upload/'.$someFile)
      

      还可以在下载时定义另一个名称:

      return $this->file('/home/website/upload/'.$someFile, 'MyFile.pdf');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多