Starting from How do I create a file download URL? I've build a custom controller that allows users to download a PDF file.


  path: '/my-module/pdf/download'
    _title: 'PDF download'
    _controller: '\Drupal\my_module\Controller\MyModuleController::downloadPDF'
    _role: 'authenticated'


public function downloadPDF() {
  $pdf_stream = $this->restCallThatReturnAPdfStream();

  $headers = [
    'Content-Type' => 'application/pdf',
    'Content-Disposition' => 'attachment;filename="download.pdf"'

  $temporary_pdf_file = $this->fileSystem->saveData($pdf_stream, 'temporary://mytempfile.pdf', FileSystemInterface::EXISTS_REPLACE); 

  return new BinaryFileResponse($temporary_pdf_file, 200, $headers, TRUE);

This file must be private per user, so other users shouldn't be able to download it.

I think I could delete the file after the controller returns the response, instead of implementing some complex access control check for the file, but I've no clue how I can easily do.

For example, I could set a Cron queue to delete those files every N minutes, but it seems an overkill.

I cannot also change when temporary files are deleted because those files are used elsewhere in the site and I wouldn't risk to break some other existing logic.

1 Answer 1


You're looking for BinaryFileResponse::deleteFileAfterSend:

$response = new BinaryFileResponse($temporary_pdf_file, 200, $headers, TRUE);
return $response->deleteFileAfterSend(TRUE);
  • Thank you, it was right under my nose but I could find it xD
    – Giuseppe
    Jul 23, 2021 at 7:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.