如何允许在 drupal 中下载文件?
How do I allow download of a file in drupal?
我有一份报告,我希望允许用户将当前数据提取到可下载的 .csv 文件中。
我目前正在使用 unmanaged_write_submit 但这只会将 csv 打印到屏幕上,用户必须右键单击并另存为。我想让它尽可能简单,允许通过单击按钮下载实际文件。
$page['submit'] = array(
'#type' => 'submit',
'#value' => 'Download Report',
'#submit' => array('test_unmanaged_write_submit'),
);
function test_unmanaged_write_submit($form, &$form_state) {
//$data is pulling the .csv/query data
$data = get_array_data($form,&$form_state);
$destination = !empty($form_state['values']['destination']) ? $form_state['values']['destination'] : NULL;
// With the unmanaged file we just get a filename back.
$filename = file_unmanaged_save_data($data, $destination, FILE_EXISTS_REPLACE);
if ($filename) {
$url = file_create_url($filename);
$_SESSION['file_example_default_file'] = $filename;
drupal_set_message(t('Saved file as %filename (accessible via !url, uri=<span id="uri">@uri</span>)', array(
'%filename' => $filename,
'@uri' => $filename,
'!url' => l(t('this URL'), $url),
)));
}
else {
drupal_set_message(t('Failed to save the file'), 'error');
}
}
但这只会向在屏幕上显示 .csv 的网页提供 link。在 php 中是否有其他 drupal 函数或方法来强制下载文件?
自从我使用 Drupal 以来已经有一段时间了,但基于提供的答案 here。
您可以将 $form_state
数组中的重定向变量设置为文件的 URL。所以基本上只需从您对 file_create_url
的调用中获取 $url
并将其粘贴到重定向中:
$form_state['redirect'] = $url;
如果这不起作用,您可以按照 here.
中所述使用纯 PHP 来完成
我有一份报告,我希望允许用户将当前数据提取到可下载的 .csv 文件中。
我目前正在使用 unmanaged_write_submit 但这只会将 csv 打印到屏幕上,用户必须右键单击并另存为。我想让它尽可能简单,允许通过单击按钮下载实际文件。
$page['submit'] = array(
'#type' => 'submit',
'#value' => 'Download Report',
'#submit' => array('test_unmanaged_write_submit'),
);
function test_unmanaged_write_submit($form, &$form_state) {
//$data is pulling the .csv/query data
$data = get_array_data($form,&$form_state);
$destination = !empty($form_state['values']['destination']) ? $form_state['values']['destination'] : NULL;
// With the unmanaged file we just get a filename back.
$filename = file_unmanaged_save_data($data, $destination, FILE_EXISTS_REPLACE);
if ($filename) {
$url = file_create_url($filename);
$_SESSION['file_example_default_file'] = $filename;
drupal_set_message(t('Saved file as %filename (accessible via !url, uri=<span id="uri">@uri</span>)', array(
'%filename' => $filename,
'@uri' => $filename,
'!url' => l(t('this URL'), $url),
)));
}
else {
drupal_set_message(t('Failed to save the file'), 'error');
}
}
但这只会向在屏幕上显示 .csv 的网页提供 link。在 php 中是否有其他 drupal 函数或方法来强制下载文件?
自从我使用 Drupal 以来已经有一段时间了,但基于提供的答案 here。
您可以将 $form_state
数组中的重定向变量设置为文件的 URL。所以基本上只需从您对 file_create_url
的调用中获取 $url
并将其粘贴到重定向中:
$form_state['redirect'] = $url;
如果这不起作用,您可以按照 here.
中所述使用纯 PHP 来完成