开发者

Download files with zend contextSwitch() Action Helper

开发者 https://www.devze.com 2023-03-08 21:05 出处:网络
everybody. I\'m stack with similar thing: i have to provide a download file capability with Zend Framework... Several hours of googling don\'t help me with this...

everybody. I'm stack with similar thing: i have to provide a download file capability with Zend Framework... Several hours of googling don't help me with this... So here is my Controller code (note: i'm a beginner):

//callback
public function sendFile()
{
    readfile(APPLICATION_PATH . "/../public/pdf/10.pdf");
}

public function init()
{
    $this->_helper->contextSwitch()
            ->addContext('file', array(
                  'headers' => array(
                      'Content-Type'          => 'application/pdf',
                      'Content-disposition'   => 'attachment; filename="10.pdf"'),
    开发者_如何学C              'callbacks' => array(
                      'init'  => '_sendFile'
                  )
              ))
            ->addActionContext('download', 'file')
            ->setAutoJsonSerialization(false)
            ->initContext();

}
// ...
public function downloadAction()
{
}

PS: I find this download files with zend framework but i want to do this Zend way. Thank you all


You could try.

public function init()
{
    $this->_helper->contextSwitch()
            ->addContext('file'))
            ->addActionContext('download', 'file')
            ->setAutoJsonSerialization(false)
            ->initContext();

}
// ...
public function downloadAction()
{
    if ($this->_helper->contextSwitch()->getCurrentContext() == 'file') {
        $this->getResponse()
                ->setHeader('Content-type', 'application/pdf; charset=binary')
                ->setHeader('Content-Disposition', 'attachment; filename="10.pdf"')
                ->setHeader('Content-length', filesize(APPLICATION_PATH . "/../public/pdf/10.pdf"))
                ->setHeader('Cache-control', 'private');
        readfile(APPLICATION_PATH . "/../public/pdf/10.pdf");
        $this->getResponse()->sendResponse();
    } else {
        throw new Zend_Controller_Action_Exception('File not found', 404);
    }
}

You must also set the parameter format to file either as a POST or GET variable in the calling page, for example.

<a href="http://yourdomain.com/path/to/controller/format/file">

If your file is in your public documents folder you could just simply link to it directly.

<a href="http://yourdomain.com/pdf/10.pdf">

and not bother with the above PHP/ZF code.

I hope this helps.

Kind regards

Garry

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号