Skip to content

Commit d7a3d56

Browse files
committed
Allow set custom Content-Type for downloads
1 parent 70dcf94 commit d7a3d56

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

src/ResponseDownload.php

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ trait ResponseDownload
3939
private $handle;
4040
private int $delay = 0;
4141
private int $readLength = 1024;
42+
private ?string $contentType = null;
4243

4344
/**
4445
* Sets a file to download/stream.
@@ -75,6 +76,7 @@ public function setDownload(
7576
$this->filepath = $realpath;
7677
$this->delay = $delay;
7778
$this->readLength = $readLength;
79+
$this->contentType = $contentType;
7880
$filesize = @\filesize($this->filepath);
7981
if ($filesize === false) {
8082
throw new RuntimeException(
@@ -108,14 +110,17 @@ public function setDownload(
108110
}
109111
}
110112
$this->setHeader(ResponseHeader::CONTENT_LENGTH, (string) $this->filesize);
111-
if ($contentType === null) {
112-
$contentType = \mime_content_type($this->filepath) ?: 'application/octet-stream';
113-
}
114-
$this->setHeader(ResponseHeader::CONTENT_TYPE, $contentType);
113+
$this->setHeader(ResponseHeader::CONTENT_TYPE, $this->makeContentType());
115114
$this->sendType = 'normal';
116115
return $this;
117116
}
118117

118+
private function makeContentType() : string
119+
{
120+
return $this->contentType
121+
?? \mime_content_type($this->filepath) ?: 'application/octet-stream';
122+
}
123+
119124
private function prepareRange(string $rangeLine) : void
120125
{
121126
$this->byteRanges = $this->parseByteRange($rangeLine);
@@ -223,7 +228,7 @@ private function setSinglePart(int $firstByte, int $lastByte) : void
223228
);
224229
$this->setHeader(
225230
ResponseHeader::CONTENT_TYPE,
226-
\mime_content_type($this->filepath) ?: 'application/octet-stream'
231+
$this->makeContentType()
227232
);
228233
$this->setHeader(
229234
ResponseHeader::CONTENT_RANGE,

tests/ResponseDownloadTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,15 @@ public function testReadFileWithDelay() : void
221221
}
222222

223223
public function testContentType() : void
224+
{
225+
$filepath = __DIR__ . '/files/logo.png';
226+
$this->response->setDownload($filepath);
227+
self::assertSame('image/png', $this->response->getHeader('Content-Type'));
228+
$this->response->setDownload($filepath, contentType: 'foo/bar');
229+
self::assertSame('foo/bar', $this->response->getHeader('Content-Type'));
230+
}
231+
232+
public function testContentTypeWithoutAcceptRanges() : void
224233
{
225234
$filepath = __DIR__ . '/files/logo.png';
226235
$this->response->setDownload($filepath, acceptRanges: false);

0 commit comments

Comments
 (0)