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';
$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/');
  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);

7 comments for 'Simple example of how to use Drupal to serve file downloads'

Mitchell's picture

You could import / upload the files to Drupal and render them with Entity API to produce an output similar to the one above using, for example, RestWS. See:
* Request Handler#mimeType
* Example File Output

A simpler renderer is Entity JSON, but I'm not sure how well file fields would work (would be a good report). Services is also an option, but that's not as simple.

Thanks for the article, very insightful example.
PS. this captcha thing is a b*.

admin's picture

By using the snippet above, still gives you a little bit more control and flexibility, say you want to unlink() the file right after being served?

Unless you can do that with file_transfer() that will be awesome!

Because, that function calls drupal_exit() in the end.

admin's picture

Whoa thanks for sharing these modules. I've never tried RestWS personally but it does looks like it could give a helping hand in the future projects for Web Services.

Btw, the Captcha stuff, I can't help it. Been spammed like mad. Previously tried Mollom's Captcha (seems easier to read), but it still gives room for spammers to bypass somehow... In the end had to go back to REcaptcha =(