<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
class TestController extends ControllerBase {
public function forceDownloadFile() {
$file = 'public://slides.pdf';
$filename = 'the-slides.pdf';
$response = new BinaryFileResponse($file);
$response->headers->set('Content-Type', 'application/pdf');
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);
return $response;
}
}
The route to this controller action would look like this:
mymodule_download:
path: '/download'
defaults:
_controller: '\Drupal\mymodule\Controller\TestController::forceDownloadFile'
requirements:
_access: 'TRUE'
When the user visits the page at /download they will automatically download the pdf file.
Add new comment