symfony - 下载文件

2022-01-11 00:00:00 download header php symfony

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

I am trying download files in controller but in the console I see only really bunch of weird characters instead of download box. I am following this topic Symfony2 - Force file download.

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

Don't know what is going on... trying to find simplest solution. Here is my code:

 $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() 的最基本示例.我的服务器需要特殊配置吗?干杯.

I've even tried to use the most basic example with header() and readfile(). Does my server need special config or something? Cheers.

推荐答案

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

Instead of rebuilding that kind of response, you could use Symfony's built-inBinaryFileResponse.

use SymfonyComponentHttpFoundationBinaryFileResponse;

$response = new BinaryFileResponse($file);

还请查看关于提供文件的文档.

相关文章