Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework 2 file download

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.

like image 605
Danizord Avatar asked Apr 18 '13 20:04

Danizord


2 Answers

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

like image 178
hussfelt Avatar answered Oct 14 '22 22:10

hussfelt


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;
}
like image 38
Athlan Avatar answered Oct 14 '22 22:10

Athlan