Drupal 9: Controller Action To Force Download A File

<?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

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