Delete unmanaged file after download?
-
29-09-2020 - |
Question
In a custom module I create a file and then use drupal_goto
to download it. How can I delete the file after it is downloaded? Placing a file_unmanaged_delete
after the drupal_goto
doesn't get executed, and hook_file_download
happens before the download for permissions checks and such. So I'm not sure how to do this. Do I have to resort to cleaning up files in a folder with cron somehow?
No correct solution
OTHER TIPS
// Generate pdf card.
$file_path = $crm_card->generatePdfCard();
$filename = basename($file_path);
$headers = [
'Content-Type' => 'application/octet-stream',
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
'Content-Length' => filesize($file_path),
];
$binary_file_response = new BinaryFileResponse($file_path, 200, $headers);
$binary_file_response->deleteFileAfterSend(TRUE);
return $binary_file_response;
The following code will remove the file after download considering that your file is located in tmp directory.
$filename = 'foobar.xls';
$temp_path = realpath(file_directory_temp()) . '/';
if (file_exists($temp_path . $filename)) {
// Serve file download.
drupal_add_http_header('Pragma', 'public');
drupal_add_http_header('Expires', '0');
drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
drupal_add_http_header('Content-Type', 'application/vnd.ms-excel');
drupal_add_http_header('Content-Disposition', 'attachment; filename=' . basename($temp_path . $filename) . ';');
drupal_add_http_header('Content-Transfer-Encoding', 'binary');
drupal_add_http_header('Content-Length', filesize($temp_path . $filename));
readfile($temp_path . $filename);
unlink($temp_path . $filename);
drupal_exit();
}
You can visit the following link for details http://kahthong.com/2012/08/simple-example-how-use-drupal-serve-file-downloads
Thanks!
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange