9 – How can I delete a file served by a custom controller after it has been downloaded?

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: 'Drupalmy_moduleControllerMyModuleController::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.