Search This Blog

Thursday, December 16, 2010

How to download files in Symfony

Its very easy to download files in symfony. Create a proper action and do something like this , i have assumes that files are stored in the database and its a pdf file. But you can assign any file by storing the file type in the database.



public function  executeDownloadFile(sfWebRequest $request) {
        $yourfileData = '' // get your file data from the database
        $this->getResponse()->clearHttpHeaders();
        $this->getResponse()->setHttpHeader('Content-Disposition',
        'attachment; filename='. 'myfile.pdf');
        $this->getResponse()->setContentType('application/pdf');
        $this->getResponse()->sendHttpHeaders();       
        $this->getResponse()->setContent($yourfileData);

        return sfView::NONE;

}

If you need to set http headers 

private function setHttpHeaders($size, $fileName, $contentType='application/csv') {
        $this->getResponse()->clearHttpHeaders();
        $this->getResponse()->addCacheControlHttpHeader('Cache-control', 'private');
        $this->getResponse()->setHttpHeader('Content-Description', 'File Transfer');
        $this->getResponse()->setContentType($contentType, TRUE);
        $this->getResponse()->setHttpHeader('Content-Length', (string) $size, TRUE);
        $this->getResponse()->setHttpHeader('content-transfer-encoding', 'binary', TRUE);
        $this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename=' . $fileName, TRUE);
        $this->getResponse()->sendHttpHeaders();
    }

No comments: