Drupal - How can I upload files with the form element type file?

I had the same problem with the file form element. Solved this by using managed_file and providing the upload location and validators in the form element:

$form['test_CERTIFICATE'] = [
  '#type' => 'managed_file',
  '#title' => $this->t('Certificate'),
  '#upload_location' => 'private://certfiles',
  '#upload_validators' => [
    'file_validate_extensions' => ['pem'],
  ],
];

Then in submit:

use Drupal\file\Entity\File;

$form_file = $form_state->getValue('test_CERTIFICATE', 0);
if (isset($form_file[0]) && !empty($form_file[0])) {
  $file = File::load($form_file[0]);
  $file->setPermanent();
  $file->save();
}

You can access files data uploaded through "file" field using the following code (from D8.5 core/modules/config/src/Form/ConfigImportForm.php)

$all_files = $this->getRequest()->files->get('files', []);
$file = $all_files['test_CERTIFICATE'];
$file_path = $file->getRealPath();

Tags:

Forms

8