diff --git a/system/HTTP/DownloadResponse.php b/system/HTTP/DownloadResponse.php index 067dbcd7028f..e4960a72c3f7 100644 --- a/system/HTTP/DownloadResponse.php +++ b/system/HTTP/DownloadResponse.php @@ -138,6 +138,19 @@ public function setFilePath(string $filepath) $this->file = new File($filepath, true); } + /** + * set name for the download. + * + * @param string $filename + * + * @return $this + */ + public function setFileName(string $filename) + { + $this->filename = $filename; + return $this; + } + /** * get content length. * diff --git a/tests/system/HTTP/DownloadResponseTest.php b/tests/system/HTTP/DownloadResponseTest.php index 48560f593942..5d4dcf2c6a97 100644 --- a/tests/system/HTTP/DownloadResponseTest.php +++ b/tests/system/HTTP/DownloadResponseTest.php @@ -95,6 +95,15 @@ public function testSetContentTypeNoCharSet() $this->assertEquals('application/octet-stream', $response->getHeaderLine('Content-Type')); } + + public function testSetFileName() + { + $response = new DownloadResponse('unit-test.txt', true); + $response->setFileName('myFile.txt'); + $response->buildHeaders(); + + $this->assertSame('attachment; filename="myFile.txt"; filename*=UTF-8\'\'myFile.txt', $response->getHeaderLine('Content-Disposition')); + } public function testNoCache() { diff --git a/user_guide_src/source/outgoing/response.rst b/user_guide_src/source/outgoing/response.rst index 5405eb41756b..304985c0cd9c 100644 --- a/user_guide_src/source/outgoing/response.rst +++ b/user_guide_src/source/outgoing/response.rst @@ -100,6 +100,10 @@ do the following:: // Contents of photo.jpg will be automatically read return $response->download('/path/to/photo.jpg', NULL); +Use the optional ``setFileName()`` method to change the filename as it is sent to the client's browser:: + + return $response->download('awkwardEncryptedFileName.fakeExt')->setFileName('expenses.csv'); + .. note:: The response object MUST be returned for the download to be sent to the client. This allows the response to be passed through all **after** filters before being sent to the client.