Score:1

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

br flag

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.

Score:1
cn flag

You're looking for BinaryFileResponse::deleteFileAfterSend:

$response = new BinaryFileResponse($temporary_pdf_file, 200, $headers, TRUE);
return $response->deleteFileAfterSend(TRUE);
Giuseppe avatar
br flag
Thank you, it was right under my nose but I could find it xD
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.