【发布时间】: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 时,我将标题内容写入浏览器窗口。