Zend Framework 2 file download

2019-03-16 17:44发布

问题:

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.

回答1:

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;
}


回答2:

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