【问题标题】:Send attachment/Download file from Symfony action从 Symfony 操作发送附件/下载文件
【发布时间】:2012-03-28 04:07:37
【问题描述】:

我正在尝试通过操作传递 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;

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

【问题讨论】:

  • 这有点过头了——应该不需要 HEADER_ONLY 和 sendHttpHeaders,但其余部分很好地概述了像静态文件服务器一样提供服务所需的条件。

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


【解决方案1】:

试试这样的:

$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

【讨论】:

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