Simple example of how to use Drupal to serve file downloads
Ever been in a situation whereby you want to serve file download via Drupal? Such as exporting nodes to CSV, etc. Well this tutorial is for you.
Disclaimer: This may not be the best way. Please do suggest if you have a better way.
This tutorial assumes your file to serve as download is located in the temp folder and it will be deleted after download is served.
$filename = 'foobar.xls';<br>$temp_path = realpath(file_directory_temp()) . '/';<p>if (file_exists($temp_path . $filename)) {<br> // Serve file download.<br> drupal_add_http_header('Pragma', 'public');<br> drupal_add_http_header('Expires', '0');<br> drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');<br> drupal_add_http_header('Content-Type', 'application/vnd.ms-excel');<br> drupal_add_http_header('Content-Disposition', 'attachment; filename=' . basename($temp_path . $filename) . ';');<br> drupal_add_http_header('Content-Transfer-Encoding', 'binary');<br> drupal_add_http_header('Content-Length', filesize($temp_path . $filename));<br> readfile($temp_path . $filename);<br> unlink($temp_path . $filename);<br> drupal_exit();<br>}</p>
Tags: drupaldrupal 7file downloaddownloadstreamheader