【问题标题】:How to upload file in Drupal 7 with forms?如何在 Drupal 7 中使用表单上传文件?
【发布时间】:2010-11-20 14:19:09
【问题描述】:

我在使用 Drupal 7 和文件上传时遇到问题。

我的代码不起作用:

function test_form($form, &$form_state){

$form['#attributes'] = array('enctype' => "multipart/form-data");
$form['podcast'] = array(
    '#title' => 'Audio file',
    '#type' => 'file',
);
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
);
return $form;

}

function test_form_submit($form, &$form_state){

$vals = $form_state['values'];
$filepath = 'public://test/';
//$filepath = 'temporary://test/';
$filename = 'rcc_date.mp3';

file_prepare_directory($filepath, FILE_CREATE_DIRECTORY);
$file = file_save_upload('podcast', array('file_validate_extensions' => array()), $filepath.$filename);
//got FALSE here. Why?
die(print_r($file===FALSE).'-');

}

因此创建了路径,但文件未上传,并且 file_save_upload 返回 FALSE。我也尝试了 array() 和 true 作为 $validators 没有效果。

非常感谢任何帮助。谢谢。

【问题讨论】:

  • 如何动态获取文件名?
  • 此代码中完全不需要文件名。完全离开它。不要设置 $filename 变量,也不要将其附加到 $filepath。
  • 使用空的文件验证器数组,如 array('file_validate_extensions' => array()),是不安全的,不应使用。改为使用 NULL 来获取默认值,或者自己制作一个真实的列表。请参阅api.drupal.org/api/drupal/includes!file.inc/function/…中的注释

标签: drupal file-upload drupal-7


【解决方案1】:

哦。 $destination 不应该包含文件名,只包含路径。

【讨论】:

  • 对于那些想知道 $destination 在哪里的人,它是 file_save_upload 的第三个参数。该行应如下所示: $file = file_save_upload('podcast', array('file_validate_extensions' => array()), $filepath);或者最好像这样: $file = file_save_upload('podcast', null, $filepath);这要安全得多。例如,它不允许上传 PHP 文件,这将是一个巨大的安全风险。见api.drupal.org/api/drupal/includes!file.inc/function/…
猜你喜欢
  • 2012-06-16
  • 1970-01-01
  • 2010-11-18
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-16
相关资源
最近更新 更多