I have a Drupal 7 site. After some form actions, I want the user to be able to click on a link to download a csv file of the results, but I don't need the csv hanging around the site forever. I have the file being written to the temporary file system using the temporary:// streamwrapper.

Is there functionality in core that can offer this file for download? If so, what is it? Or else, do I need to/can I write a menu callback function that sets the mime header and all that?


Here's how I did it. I saved a file using file_unmanaged_save_data()

$file = file_unmanaged_save_data($csv, "temporary://" . $filename, FILE_EXISTS_RENAME);

Then I made a menu callback that was just MENU_CALLBACK, which calls this:

function download_file($filename) {
  $filename = t($filename);
  drupal_add_http_header('Content-type', 'application/csv; charset=ISO-8859-1');
  drupal_add_http_header('Content-Disposition', 'attachment; filename=\'output.csv\'');
  echo file_get_contents('temporary://' . $filename);

I should add an additional check to make sure that the file exists before echoing its contents.

|improve this answer|||||
  • 1
    Drupal has a function for this, you don't need to roll your own. Ref file_transfer() – pfrenssen Aug 18 '14 at 18:11

The project Examples has a File Example module demonstrating the Drupal File API (and Stream Wrappers).

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.