Skip to content

Instantly share code, notes, and snippets.

@dpasqua
Created September 2, 2013 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpasqua/6416496 to your computer and use it in GitHub Desktop.
Save dpasqua/6416496 to your computer and use it in GitHub Desktop.
Exemplo de como implementar download de arquivos no zend framework2 de forma eficiente!
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class DownloadController extends AbstractActionController
{
public function indexAction()
{
$response = $this->createStreamResponseFromFile("/var/www/arquivo.zip");
if($response) {
return $response;
}
echo "arquivo não encontrado";
return $this->response;
}
/**
* Cria stream de resposta http a partir de um arquivo
* Função utilizada para implementar download de arquivos no zf2
* @param string $filepath
* @return \Zend\Http\Response\Stream
*/
public static function createStreamResponseFromFile($filepath)
{
if(!file_exists($filepath)) {
return false;
}
$response = new \Zend\Http\Response\Stream();
$response->setStream(fopen($filepath, 'r'));
$response->setStatusCode(200);
$response->setStreamName(basename($filepath));
$headers = new \Zend\Http\Headers();
$headers->addHeaders(array(
'Content-Disposition' => 'attachment; filename="' . basename($filepath) .'"',
'Content-Type' => 'application/octet-stream',
'Content-Length' => filesize($filepath)
));
$response->setHeaders($headers);
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment