0

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?

Raj
  • 22,346
  • 14
  • 99
  • 142

1 Answers1

4

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?

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • @emaillenin yes. You may have to tweak the headers for it to work in all browsers but yes, if `content-disposition` is `attachment` the download dialog will appear. – Pekka Dec 21 '10 at 11:34
  • @emaillenin see e.g. this answer for a complete set of headers: http://stackoverflow.com/questions/3718962/force-file-download-in-php/3719287#3719287 – Pekka Dec 21 '10 at 11:36
  • Thanks. It didnt work over AJAX. I tried simple header and readfile functions and it worked. – Raj Dec 21 '10 at 17:32