Skip to content

Commit

Permalink
#345 - Add support for force downloading files
Browse files Browse the repository at this point in the history
Add support for the 'force-download' query parameter. If specified the
file will be downloaded instead of allowing the browser to preview the
file if it can do so.

For example:

'files/[:name]' => '/files/documents/[:name].pdf?force-download'
  • Loading branch information
johanjanssens committed May 16, 2020
1 parent 8b0d487 commit 10514ab
Showing 1 changed file with 39 additions and 35 deletions.
74 changes: 39 additions & 35 deletions code/site/components/com_pages/event/subscriber/downloader.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,38 +9,42 @@

class ComPagesEventSubscriberDownloader extends ComPagesEventSubscriberAbstract
{
protected function _initialize(KObjectConfig $config)
{
$config->append(array(
'priority' => KEvent::PRIORITY_HIGH,
));

parent::_initialize($config);
}

public function onAfterApplicationRoute(KEventInterface $event)
{
$request = $this->getObject('request');
$router = $this->getObject('com://site/pages.dispatcher.router.file', ['request' => $request]);

if(false !== $route = $router->resolve())
{
//Qualify the route
$path = (string) $router->qualify($route, true);

//Set the location header
$dispatcher = $this->getObject('com://site/pages.dispatcher.http');

try
{
$dispatcher->getResponse()
->setContent((string) $path, @mime_content_type($path) ?? 'application/octet-stream');
}
catch (InvalidArgumentException $e) {
throw new KControllerExceptionResourceNotFound('File not found');
}

$dispatcher->send();
}
}
}
protected function _initialize(KObjectConfig $config)
{
$config->append(array(
'priority' => KEvent::PRIORITY_HIGH,
));

parent::_initialize($config);
}

public function onAfterApplicationRoute(KEventInterface $event)
{
$request = $this->getObject('request');
$router = $this->getObject('com://site/pages.dispatcher.router.file', ['request' => $request]);

if(false !== $route = $router->resolve())
{
//Qualify the route
$route = $router->qualify($route);

//Get the file path
$path = $route->getPath();

if(isset($route->query['force-download'])) {
$request->query->set('force-download', true);
}

//Set the location header
$dispatcher = $this->getObject('com://site/pages.dispatcher.http');

try {
$dispatcher->getResponse()->setContent($path, @mime_content_type($path) ?? 'application/octet-stream');
} catch (InvalidArgumentException $e) {
throw new KControllerExceptionResourceNotFound('File not found');
}

$dispatcher->send();
}
}
}

0 comments on commit 10514ab

Please sign in to comment.