从Symfony行动发送附件/下载文件

时间:2012-03-28 04:07:37

标签: php http-headers symfony-1.4 download attachment

我正在尝试通过操作传递CSV文件。响应中的mime类型仍显示为text / html。有人可以帮忙吗?感谢

        //$this->setLayout(false);
        //$this->getUser()->shutdown();
        //sfConfig::set('sf_web_debug', false);
        $response = $this->getContext()->getResponse();
        $response = $this->getResponse();
        $response->clearHttpHeaders();
        $response->setHttpheader('Pragma: public', true);
        $response->addCacheControlHttpHeader('Cache-Control', 'must-revalidate');
        $response->setContentType('application/octet-stream', true);
        $response->setHttpHeader('Content-Description', 'File Transfer');
        $response->setHttpHeader('Content-Transfer-Encoding', 'binary', true);
        $response->setHttpHeader('Content-Length', filesize($file_path));
        $response->setHttpHeader('Content-Disposition', 'attachment; filename="' . $file_name . '"');
        $this->getResponse()->sendHttpHeaders();
        //$response->setContent(file_get_contents($file_path));
        //readfile($file_path);
        $this->renderText(file_get_contents($file_path));
        //return sfView::NONE;

        return sfView::HEADER_ONLY;

相信我,在到达这里之前,我所有的搜索结果都是紫色的。你可以看到所有的排列和&上面的组合,我仍然无法得到这个工作!

1 个答案:

答案 0 :(得分:6)

尝试这样的事情:

$path = 'absolute/path/to/the/file';

/** @var $response sfWebResponse */
$response = $this->getResponse();

$response->setContentType('text/csv');
$response->setHttpHeader('Content-Disposition', 'attachment; filename="' . basename($path) . '"');
$response->setContent(file_get_contents($path));

return sfView::NONE;

注意:文件名必须为ASCII,请参阅RFC 6266