Last active
December 16, 2015 02:59
-
-
Save drahak/5366258 to your computer and use it in GitHub Desktop.
FilePresenter with actions view & download. Requires fileinfo extension to determine right content type.
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 | |
use Drahak\Application\Responses\FileViewResponse, | |
Nette\Application\Responses\FileResponse; | |
/** | |
* FilePresenter | |
* @author Drahomír Hanák | |
*/ | |
class FilePresenter extends BasePresenter | |
{ | |
/** | |
* Triggers file view | |
* @param string $file | |
*/ | |
public function actionView($file) | |
{ | |
$this->sendResponse(new FileViewResponse('files/' . $file)); | |
} | |
/** | |
* Triggers file download | |
* @param stirng $file | |
*/ | |
public function actionDownload($file) | |
{ | |
$this->sendResponse(new FileResponse('files/' . $file)); | |
} | |
} |
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 Drahak\Application\Responses; | |
use Nette, | |
Nette\Http\IRequest, | |
Nette\Http\IResponse, | |
Nette\Utils\MimeTypeDetector; | |
/** | |
* FileViewResponse | |
* @author Drahomír Hanák | |
* | |
* @property-read string $contentType | |
* @property-read string $file | |
*/ | |
class FileViewResponse extends Nette\Object implements Nette\Application\IResponse | |
{ | |
/** @var string */ | |
private $file; | |
/** @var string */ | |
private $contentType; | |
public function __construct($file = NULL) | |
{ | |
$this->file = $file; | |
if (!file_exists($this->file)) { | |
throw new Nette\Application\BadRequestException('File ' . $this->file . ' does not exist.'); | |
} | |
$this->contentType = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this->file); | |
} | |
/** | |
* Get content type | |
* @return string | |
*/ | |
final public function getContentType() | |
{ | |
return $this->contentType; | |
} | |
/** | |
* Get file path | |
* @return string | |
*/ | |
final public function getFile() | |
{ | |
return $this->file; | |
} | |
/** | |
* Sends response to output | |
* @param IRequest $httpRequest | |
* @param IResponse $httpResponse | |
* @return void | |
*/ | |
public function send(IRequest $httpRequest, IResponse $httpResponse) | |
{ | |
$httpResponse->setContentType($this->contentType); | |
echo file_get_contents($this->file); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment