开发者

Saving Data from Drupal to Local System File

开发者 https://www.devze.com 2022-12-20 11:25 出处:网络
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

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 docume开发者_StackOverflow中文版ntation 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消