Exemplo de como implementar download de arquivos no zend framework2 de forma eficiente!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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