【发布时间】:2013-01-03 16:11:04
【问题描述】:
当然,其他人已经在 stackoverflow 上讨论过这些问题,但并非所有分析器都适合我,而且他们通常不提供 symfony 安装的版本。
我阅读的主题:
- Send attachment/Download file from Symfony action
- How to download a file on clicking thefile path using PHP-Symfony?
- symfony: setHttpHeader() doesn't work, header() does
这就是我要问您如何在 symfony 1.4 中处理文件下载(不使用视图)? 在我所有的用例中,我需要一个模板文件来呈现响应。如果我发送由于控制器的响应,则唯一的可能性是在没有 php 错误(已发送标头)的情况下发送它
控制者:
/** @var $response sfWebResponse */
$response = $this->getResponse();
$response->clearHttpHeaders();
$response->setContentType($mimeType);
$response->setHttpHeader('Content-Disposition', 'attachment; filename="' . basename($filePath) . '"');
$response->setHttpHeader('Content-Description', 'File Transfer');
$response->setHttpHeader('Content-Transfer-Encoding', 'binary');
$response->setHttpHeader('Content-Length', filesize($filePath));
$response->setHttpHeader('Cache-Control', 'public, must-revalidate');
$response->setHttpHeader('Pragma', 'public');
$response->sendHttpHeaders();
readfile($filePath); die();
这无需模板文件即可工作。但是恕我直言,这不是那么漂亮的编码。
模板的替代方式:
控制者:
/** @var $response sfWebResponse */
$response = $this->getResponse();
$response->clearHttpHeaders();
$response->setContentType($mimeType);
$response->setHttpHeader('Content-Disposition', 'attachment; filename="' . basename($filePath) . '"');
$response->setHttpHeader('Content-Description', 'File Transfer');
$response->setHttpHeader('Content-Transfer-Encoding', 'binary');
$response->setHttpHeader('Content-Length', filesize($filePath));
$response->setHttpHeader('Cache-Control', 'public, must-revalidate');
$response->setHttpHeader('Pragma', 'public');
$response->setContent(file_get_contents($filePath));
$response->sendHttpHeaders();
return sfView::NONE;
查看:
<?php echo $sf_response->getRawValue()->getContent(); ?>
【问题讨论】:
-
你试过用
return $this->renderText($response->getContent());代替return sfView::NONE;吗? -
readfile方法比将内容发送到视图更好,因为前者具有内置缓冲,而后者必须完全保存在内存中,因此会更慢。跨度> -
return $this->renderText($response->getContent());在我的情况下不起作用。它不会引发任何异常,但会从浏览器中引发“找不到文件”错误。
标签: php symfony1 symfony-1.4