Send attachment/Download file from Symfony action

南笙酒味 提交于 2019-12-24 07:58:27

问题


I'm trying to deliver a CSV file through an action. The mime-type in the response still shows as text/html. Can someone help? Thanks

        //$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;

Trust me, before getting here, I've all search results purple. As you can see all the permutations & combinations above, I still couldn't get this working!


回答1:


Try something like this:

$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;

Note: filename must be ASCII see RFC 6266



来源:https://stackoverflow.com/questions/9900991/send-attachment-download-file-from-symfony-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!