Monday, October 18, 2010

Function to download file with Magento

In the controller use this function

    protected function _sendFile($pdfPath) {
        if (! is_file ( $pdfPath ) || ! is_readable ( $pdfPath )) {
            throw new Exception ( );
        }
        $this->getResponse ()
                    ->setHttpResponseCode ( 200 )
                    ->setHeader ( 'Pragma', 'public', true )
                    ->setHeader ( 'Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true )
                    /* View in browser */
                    //->setHeader ( 'Content-type', 'application/pdf', true )
                    /*  Download */
                    ->setHeader ( 'Content-type', 'application/force-download' )
                    ->setHeader ( 'Content-Length', filesize($pdfPath) )
                    ->setHeader ('Content-Disposition', 'inline' . '; filename=' . basename($pdfPath) );
        $this->getResponse ()->clearBody ();
        $this->getResponse ()->sendHeaders ();
        readfile ( $pdfPath );
        //exit(0);
    }

The passed parameter is the path of the File ( here i used this function to download a PDF file )

No comments:

Post a Comment

Powered by Blogger.