dongzhanyan3667 2010-12-21 11:22
浏览 46
已采纳

如何在Zend Framework中强制通过AJAX下载文件?

I am looking for a way to show the browser's download dialog page when a user clicks on the download button.

This is my HTML -

    <span id="ajaxdownloadcontent" class="ajaxaction ajaxbutton" 
onclick="javascript:AjaxDownloadContent('http://localhost/ajax/download/pic/12')"> 
Download </span>

My Javascript -

function AjaxDownloadContent(path) {
    $.post(path);
}

My controller, AjaxController.php -

class AjaxController extends Zend_Controller_Action {

public function init() {
    if ($this->getRequest()->isXmlHttpRequest()) {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(TRUE);
    }
}

public function downloadAction() {
    if ($this->getRequest()->isXmlHttpRequest()) {
            $this->getResponse()
                    ->clearAllHeaders()
                    ->setHeader('Content-Disposition', 'attachment;filename="Google_Logo.gif"')
                    ->sendHeaders()
                    ->setBody(file_get_contents("http://www.google.com/logos/logo.gif"))
                    ->sendResponse();
return true;
}

This is how the headers look like in firebug (Note that content type has been changed to text/html)

alt text

I think this is because of the following code in the bootstrap.

public static function sendResponse(Zend_Controller_Response_Http $response) {
    if (!headers_sent ()) {
        $response->setHeader('Content-Type', 'text/html; charset=UTF-8', true);
    }
    $response->sendResponse();
}

And finally the HTML response looks like something below -

alt text

How to force download the file(image in this case) over AJAX when the user clicks the download button?

  • 写回答

1条回答 默认 最新

  • douzhui1972 2010-12-21 11:33
    关注

    As far as I know, this is not possible using the Ajax route.

    Why not use a simple <a> tag pointing to the resource though?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记