【问题标题】:How to get filename after upload Drupal 8?上传 Drupal 8 后如何获取文件名?
【发布时间】:2018-03-02 15:03:54
【问题描述】:

我正在构建一个表单,用户可以在其中上传文件。因为我使用的是 Drupal,所以我使用的是 managed_file。文件正在上传,但我似乎无法从表单中获取文件名...这是我的代码

构建形式:

        $form['formfile'] = array(
        '#type' => 'managed_file',
        '#name' => 'formfile',
        '#title' => t('File'),
        '#upload_validators' => $validators,
        '#upload_location' => 'public://trainingrequests/',
    );

提交

drupal_set_message($form_state->getValue('formfile'));

我什么都试过了。

【问题讨论】:

  • From Form api Reference "...表单的验证和提交处理程序在 $form_state['values'] 中接收一个文件对象 ID,它表示 {file_managed} 表中新文件的 ID。 ”。现在您必须从 DB \Drupal::entityTypeManager() ->getStorage('file') ->load($file_id); 加载文件
  • 我如何获得 $file_id?

标签: drupal drupal-8


【解决方案1】:

首先需要获取File实体的实体ID,然后加载实体:

$formfile = $form_state->getValue('formfile');
if ($formfile) {
  $oNewFile = File::load(reset($formfile));
  $oNewFile->setPermanent();
  drupal_set_message('Filename: ' . $oNewFile->getFilename());
}

你可以在你的文件系统中浏览File实体的源码:core/modules/file/src/Entity/File.php

【讨论】:

    猜你喜欢
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2018-02-18
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多