Skip to content

Instantly share code, notes, and snippets.

@settermjd
Last active July 25, 2022 01:25
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save settermjd/feffc1c15a5bade95967be2229fa5537 to your computer and use it in GitHub Desktop.
Save settermjd/feffc1c15a5bade95967be2229fa5537 to your computer and use it in GitHub Desktop.
Quick example of how to download/stream a file using Zend Expressive.
<?php
/**
* This is a quick example of how to stream a file to a client, likely a browser,
* using Zend Expressive. There are a lot of factors which it doesn't take in to
* account. But for the purposes of a quick intro, this should suffice.
*/
class ViewDocumentPageAction
{
protected function downloadFile()
{
$file = 'path/to/your/file';
// create a Stream object, to stream your file to the client
$body = new Stream('php://temp', 'w+');
$body->write(file_get_contents($file));
// Return a response, containing all of the appropriate headers for
// the file that you're sending to the client. You could initialise a
// class which does all this for you, instead of having to remember
// them all by hand. But I'm keen to provide full transparency in
// this example.
return $response
->withHeader('Content-Type', 'application/octet-stream')
->withHeader(
'Content-Disposition',
"attachment; filename=" . basename($file)
)
->withHeader('Content-Transfer-Encoding', 'Binary')
->withHeader('Content-Description', 'File Transfer')
->withHeader('Pragma', 'public')
->withHeader('Expires', '0')
->withHeader('Cache-Control', 'must-revalidate')
->withBody($body)
->withHeader('Content-Length', "{$body->getSize()}");
}
}
@toralpatelin
Copy link

Hi, I have a button. on click, through ajax, i call handler method which returns the response object, exactly like shown in above example.
Now what to do on success? It's not downloading file.
function downloadSupportdoc(values) {
LYNNSTOP = 'LOOK AT VALUES';
id = values['docid'];
$.ajax({
url: "/downloads/" + id,
method: "GET",
}).done(function (response) {
$("#successAlert").html("Success - JUST TESTING.");
$("#successAlert").show("fast").delay(2500).hide("fast");

    }).fail(function (jqXHR, textStatus) {
        if (jqXHR.responseJSON !== undefined) {
            message = jqXHR.responseJSON.error.message;
        } else {
            message = jqXHR.statusText;
        }
        $("#failedAlert").html("<strong>Unable to Download Document" + id + ' ' + message + '. Please Try Again.</strong>');
        $("#failedAlert").show("fast").delay(5500).hide("fast");
    });
    return false;
}

@afilina
Copy link

afilina commented Mar 6, 2020

This has been extremely helpful for me today in refactoring a ZF1 application with header() + exit calls. Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment