【问题标题】:Download files with zend contextSwitch() Action Helper使用 zend contextSwitch() Action Helper 下载文件
【发布时间】:2011-09-04 06:30:21
【问题描述】:

大家。我有类似的事情:我必须使用 Zend Framework 提供下载文件功能......几个小时的谷歌搜索对我没有帮助...... 所以这是我的控制器代码(注意:我是初学者):

//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"'),
                  'callbacks' => array(
                      'init'  => '_sendFile'
                  )
              ))
            ->addActionContext('download', 'file')
            ->setAutoJsonSerialization(false)
            ->initContext();

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

PS:我找到了这个download files with zend framework,但我想用 Zend 的方式来做。 谢谢大家

【问题讨论】:

    标签: zend-framework controller action helper context-switch


    【解决方案1】:

    你可以试试。

    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);
        }
    }
    

    例如,您还必须将参数 format 设置为 file 作为调用页面中的 POST 或 GET 变量。

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

    如果您的文件在您的公共文档文件夹中,您可以直接链接到它。

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

    不要打扰上面的 PHP/ZF 代码。

    我希望这会有所帮助。

    亲切的问候

    加里

    【讨论】:

    • 非常感谢@Garry!你的方法成功了!但是为什么 zend 开发人员建议通过回调来实现呢? contextSwitch() callbacks非常感谢您的快速回答)
    • 还有一件事:如果我通过自己的回调 ($this->sendFile()) 执行此操作 - 它开始将原始 pdf 文件正文输出到浏览器窗口……为什么要这样做。问题出在哪里?
    • @andrew 我对上面的代码做了一些修改,这对我有用。
    • 也许我错过了 Content-length 标头的 filesize() ,它向我显示了原始数据...... H-m-m。但无论如何,非常感谢@Garry!
    猜你喜欢
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多