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: . '; filename*=utf-8\'\'' . rawurlencode($this->name));
93:
94: $filesize = $length = filesize($this->file);
95: $handle = fopen($this->file, 'r');
96:
97: if ($this->resuming) {
98: $httpResponse->setHeader('Accept-Ranges', 'bytes');
99: if (preg_match('#^bytes=(\d*)-(\d*)\z#', $httpRequest->getHeader('Range'), $matches)) {
100: list(, $start, $end) = $matches;
101: if ($start === '') {
102: $start = max(0, $filesize - $end);
103: $end = $filesize - 1;
104:
105: } elseif ($end === '' || $end > $filesize - 1) {
106: $end = $filesize - 1;
107: }
108: if ($end < $start) {
109: $httpResponse->setCode(416);
110: return;
111: }
112:
113: $httpResponse->setCode(206);
114: $httpResponse->setHeader('Content-Range', 'bytes ' . $start . '-' . $end . '/' . $filesize);
115: $length = $end - $start + 1;
116: fseek($handle, $start);
117:
118: } else {
119: $httpResponse->setHeader('Content-Range', 'bytes 0-' . ($filesize - 1) . '/' . $filesize);
120: }
121: }
122:
123: $httpResponse->setHeader('Content-Length', $length);
124: while (!feof($handle) && $length > 0) {
125: echo $s = fread($handle, min(4e6, $length));
126: $length -= strlen($s);
127: }
128: fclose($handle);
129: }
130:
131: }
132: