6

I made a form to upload files to the folder ./data/uploads using the Zend\Filter\File\RenameUpload filter.

This is working like a charm. My problem now is how do I provide this file to users download it?

I think it would be something like:

$response->setContent(file_get_contents('./data/uploads/file.png'));

But I want to know what is the best way to do this.

Wilt
  • 41,477
  • 12
  • 152
  • 203
Danizord
  • 433
  • 1
  • 4
  • 7
  • 1
    possible duplicate of [force download using ZF2](http://stackoverflow.com/questions/15219873/force-download-using-zf2) – Makoto May 24 '13 at 05:46

2 Answers2

15

For anyone who bumps into this thread looking for an answer, this is a solution that works, and it's using streams!

public function downloadAction() {
    $fileName = 'somefile';

    $response = new \Zend\Http\Response\Stream();
    $response->setStream(fopen($fileName, 'r'));
    $response->setStatusCode(200);

    $headers = new \Zend\Http\Headers();
    $headers->addHeaderLine('Content-Type', 'whatever your content type is')
            ->addHeaderLine('Content-Disposition', 'attachment; filename="' . $fileName . '"')
            ->addHeaderLine('Content-Length', filesize($fileName));

    $response->setHeaders($headers);
    return $response;
}

Found here: force download using zf2

More details here: sending stream responses with zend

Community
  • 1
  • 1
hussfelt
  • 251
  • 3
  • 12
14

Thanks to @henrik for response, but several important headers are missing in his answer. Be careful of that.

Full headers stack:

public function downloadAction() {
    $file = 'path/to/file';
    $response = new \Zend\Http\Response\Stream();
    $response->setStream(fopen($file, 'r'));
    $response->setStatusCode(200);
    $response->setStreamName(basename($file));
    $headers = new \Zend\Http\Headers();
    $headers->addHeaders(array(
        'Content-Disposition' => 'attachment; filename="' . basename($file) .'"',
        'Content-Type' => 'application/octet-stream',
        'Content-Length' => filesize($file),
        'Expires' => '@0', // @0, because zf2 parses date as string to \DateTime() object
        'Cache-Control' => 'must-revalidate',
        'Pragma' => 'public'
    ));
    $response->setHeaders($headers);
    return $response;
}
Athlan
  • 6,389
  • 4
  • 38
  • 56