Hi folk. I'm new to Drupal, and am trying to write a file upload form, so I can get the file contents into another database. 

I wrote a module called FileUpload, that consists of a FileUploadForm. I used a managed_file field in the form, and called it "file". Now I'm trying to read the file contents, and display them via drupal_set_message, but I don't know enough about the file api, and documentation is somewhat scant. 

Here's what I have so far: 

public function submitForm(array &$form, FormStateInterface $form_state) {
$file = $form_state->getValue('file');
drupal_set_message($file->get('filename'));
}

How can I read file's contents into a variable?

Comments

mmjvb’s picture

You might want to google to get the contents of a file in php, pun intended!

Trust you'll find http://php.net/manual/en/function.file-get-contents.php

thwee’s picture

Thank you, I've been googling for hours now. How do I get the filename from the $form_state->getValue('file')?

mmjvb’s picture

pass that on to the php function.

thwee’s picture

I'll try that, but from the documentation, file_get_contents expects a file name. I don't know what is returned by the getValue('file')...

mmjvb’s picture

You would need to provide a path to the file.

Maybe https://www.reddit.com/r/drupal/comments/45f001/drupal_7x_saving_an_uplo... will help

thwee’s picture

Now I get an error message: Warning, filename cannot be empty. 

jaypan’s picture

$file = $form_state->getValue('file');

You need to find out what the contents of $file are. You can use the Devel module and dpm() to find out more.


Contact me to contract me for D7 -> D10/11 migrations.
Or anything really. I'm friendly, and open to work or conversation.
jasonawant’s picture

Hi! I recently dove into this issue and came across this post. I hope to focus our collaboration in the examples module issue queue. See https://www.drupal.org/project/examples/issues/3067945

jwant