1

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

my_module.routing.yml

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

MyModuleController

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

2

You're looking for BinaryFileResponse::deleteFileAfterSend:

$response = new BinaryFileResponse($temporary_pdf_file, 200, $headers, TRUE);
return $response->deleteFileAfterSend(TRUE);
1
  • Thank you, it was right under my nose but I could find it xD
    – Giuseppe
    Commented 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.