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.