I could not find an answer anywhere, not even here, so this is my question.
In this hello example this the controller to download the file:
class DownloadController extends AbstractActionController
{
/**
* This is the default "index" action of the controller. It displays the
* Downloads page.
*/
public function indexAction()
{
return new ViewModel();
}
/**
* This is the 'file' action that is invoked
* when a user wants to download the given file.
*/
public function fileAction()
{
// Get the file name from GET variable
$fileName = $this->params()->fromQuery('name', '');
// Take some precautions to make file name secure
$fileName = str_replace("/", "", $fileName); // Remove slashes
$fileName = str_replace("\\", "", $fileName); // Remove back-slashes
// Try to open file
$path = './data/download/' . $fileName;
if (!is_readable($path)) {
// Set 404 Not Found status code
$this->getResponse()->setStatusCode(404);
return;
}
// Get file size in bytes
$fileSize = filesize($path);
// Write HTTP headers
$response = $this->getResponse();
$headers = $response->getHeaders();
$headers->addHeaderLine(
"Content-type: application/octet-stream");
$headers->addHeaderLine(
"Content-Disposition: attachment; filename=\"" .
$fileName . "\"");
$headers->addHeaderLine("Content-length: $fileSize");
$headers->addHeaderLine("Cache-control: private");
// Write file content
$fileContent = file_get_contents($path);
if($fileContent!=false) {
$response->setContent($fileContent);
} else {
// Set 500 Server Error status code
$this->getResponse()->setStatusCode(500);
return;
}
// Return Response to avoid default view rendering
return $this->getResponse();
}
}
I get this error while running it in Apache2 web-server:
A 404 error occurred
Page not found.
The requested controller was unable to dispatch the request.
Controller:
Application\Controller\DownloadController
No Exception available
But it works fine when using PHP built-in server:
php -S 0.0.0.0:8081 -t helloworld public/index.php
What am I doing wrong here?
I guess you should return $response instead of $this->getResponse(). I will show my working code for downloading file:
public function downloadAction()
{
$file = 'file content...';
$response = $this->getResponse();
$headers = $response->getHeaders();
$headers->addHeaderLine('Content-Type', 'text/csv')
->addHeaderLine('Content-Disposition', "attachment; filename=filename.csv")
->addHeaderLine("Pragma: no-cache")
->addHeaderLine("Content-Transfer-Encoding: UTF-8");
$response->setContent($file);
return $response;
}