Drupal 9: Controller Action To Force Download A File


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:

  path: '/download'
    _controller: '\Drupal\mymodule\Controller\TestController::forceDownloadFile'
    _access: 'TRUE'

When the user visits the page at /download they will automatically download the pdf file.

Add new comment

The content of this field is kept private and will not be shown publicly.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
8 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.