Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question