S
S
silentvick2015-06-23 17:43:46
Zend Framework
silentvick, 2015-06-23 17:43:46

Zend Framework 2: how to programmatically serve a file?

I am using Zend Framework 2.4. I'm trying to give the file in action. I do it like this:

public function downloadAction()
{
    // $file = ...;

    $response = new \Zend\Http\Response\Stream();
    $response->setStream(fopen($file, 'r'));
    $response->setStatusCode(200);
    $response->setStreamName(basename($file));
    $response->setContentLength(filesize($file));

    $headers = new \Zend\Http\Headers();
    $headers->addHeaderLine('Content-Type', 'application/octet-stream')
            ->addHeaderLine('Content-Disposition', 'attachment; filename="'.basename($file).'"')
            ->addHeaderLine('Content-Transfer-Encoding', 'binary')
            ->addHeaderLine('Content-Length', filesize($file))
            ->addHeaderLine('Cache-Control', 'must-revalidate')
            ->addHeaderLine('Pragma', 'public');

    $response->setHeaders($headers);

    return $response;
}

The file exists and is readable. But it loads broken (does not open). The size matches. What could be the problem here?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
silentvick, 2015-06-23
@silentvick

In general, the problem turned out to be that a space (character 0x20) is added to the response body - to the beginning. As a result, the entire contents of the file was shifted by one byte: a space byte was added to the beginning, and the last byte was not read at all, since it went beyond the limits specified in Content-Length.
Decided by calling ob_clean();before sending a response.
I have not yet understood where this unfortunate gap comes from (perhaps someone will have suggestions?). First I sinned on the closing tag ?>at the end of some file, grep went through it, but did not find anything like that.

O
OnYourLips, 2015-06-23
@OnYourLips

I would give nginx tools: wiki.nginx.org/X-accel

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question