views:

113

answers:

2

I have created a drupal module which displays some reporting data. I would like to include an option that enables a user viewing the page to save data as a txt or csv file on their local system, but I am running into the following problems:

  1. How to specify local directory to save to.
  2. How to actually save the data to the directory.

I've read through the drupal api documentation for forms. There is a 'file' input type that allows a user to browse their system and select a location to upload from. I've also looked at the file_save_data() function, but it seems that data is only saved within the drupal site directory.

Any help would be greatly appreciated.

A: 

How to specify local directory to save to.

You can't. The user's browser will save your files to either the browser's default downloads directory, or it'll prompt the user to pick a location. Letting a website pick where a file gets saved would be a major security hole - they could create desktop shortcuts to viruses, add startup items, etc.

ceejayoz
+1  A: 

This worked for me:

$file = file_save_data($data, $dest, $replace = FILE_EXISTS_RENAME); 
drupal_set_header($header = "Content-type: text");
drupal_set_header($header = "Content-Disposition: attachment; filename=$file.xls"); 
readfile($file);  
die(); 

The die() needs to go in there, or else the page html will be appended to the file.

Someone