2

I've uploaded a file in a custom form and I can retrieve the file instance like this:

  $fid = $form_state->getValue('file')[0];
  $file = File::load($fid);

How can I get the contents of the file?

kint(file_get_contents($file->url()));

Returns false. If I visit the link manually, it gets downloaded.

4

You can't get the file from $form_state->getValue(). You have to upload the file first to the file table as temporary file with file_save_upload(). Then you can load the file content locally from $file->getFileUri().

  public function submitForm(array &$form, FormStateInterface $form_state) {

    $validators = ['file_validate_extensions' => ['txt']];
    if ($file = file_save_upload('file', $validators, FALSE, 0)) {
      $data = file_get_contents($file->getFileUri());
      drupal_set_message($data);
    }

  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.