1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Application\Responses;
9:
10: use Nette;
11:
12:
13: 14: 15: 16: 17: 18: 19: 20: 21:
22: class FileResponse extends Nette\Object implements Nette\Application\IResponse
23: {
24:
25: private $file;
26:
27:
28: private $contentType;
29:
30:
31: private $name;
32:
33:
34: public $resuming = TRUE;
35:
36:
37: 38: 39: 40: 41:
42: public function __construct($file, $name = NULL, $contentType = NULL)
43: {
44: if (!is_file($file)) {
45: throw new Nette\Application\BadRequestException("File '$file' doesn't exist.");
46: }
47:
48: $this->file = $file;
49: $this->name = $name ? $name : basename($file);
50: $this->contentType = $contentType ? $contentType : 'application/octet-stream';
51: }
52:
53:
54: 55: 56: 57:
58: public function getFile()
59: {
60: return $this->file;
61: }
62:
63:
64: 65: 66: 67:
68: public function getName()
69: {
70: return $this->name;
71: }
72:
73:
74: 75: 76: 77:
78: public function getContentType()
79: {
80: return $this->contentType;
81: }
82:
83:
84: 85: 86: 87:
88: public function send(Nette\Http\IRequest $httpRequest, Nette\Http\IResponse $httpResponse)
89: {
90: $httpResponse->setContentType($this->contentType);
91: $httpResponse->setHeader('Content-Disposition', 'attachment; filename="' . $this->name . '"');
92:
93: $filesize = $length = filesize($this->file);
94: $handle = fopen($this->file, 'r');
95:
96: if ($this->resuming) {
97: $httpResponse->setHeader('Accept-Ranges', 'bytes');
98: if (preg_match('#^bytes=(\d*)-(\d*)\z#', $httpRequest->getHeader('Range'), $matches)) {
99: list(, $start, $end) = $matches;
100: if ($start === '') {
101: $start = max(0, $filesize - $end);
102: $end = $filesize - 1;
103:
104: } elseif ($end === '' || $end > $filesize - 1) {
105: $end = $filesize - 1;
106: }
107: if ($end < $start) {
108: $httpResponse->setCode(416);
109: return;
110: }
111:
112: $httpResponse->setCode(206);
113: $httpResponse->setHeader('Content-Range', 'bytes ' . $start . '-' . $end . '/' . $filesize);
114: $length = $end - $start + 1;
115: fseek($handle, $start);
116:
117: } else {
118: $httpResponse->setHeader('Content-Range', 'bytes 0-' . ($filesize - 1) . '/' . $filesize);
119: }
120: }
121:
122: $httpResponse->setHeader('Content-Length', $length);
123: while (!feof($handle) && $length > 0) {
124: echo $s = fread($handle, min(4e6, $length));
125: $length -= strlen($s);
126: }
127: fclose($handle);
128: }
129:
130: }
131: