Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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