7

I am using hook_node_presave() to build a module (which I am new to) in Drupal 7. I am able to reference fields via $node->field_foo[$node->language][0]['value'] (which I have seen mentioned several times here in Drupal Answers).

This particular content type I am working on has the ability to upload files. I am new to Drupal 7, but I noticed that:

  1. First, the user uploads the file
  2. Then, the user saves the node (with a reference to the file)

How do I access the content of that file after it has been uploaded, with hook_node_presave()?

13

The ['value'] value is typically found on fields that just store 1 kind of thing, like a text field. Other field types use whatever they need – case in point, the file field type will have an array of many values:

$node->field_some_file_field_name['und'][0] = array(
  fid => 650, // The file ID, which is important and cool.
  display => 1, // Show the file when a user views the node.
  description => 'foo', 
  uid => 7, // The user ID who uploaded this file.
  filename => some_file.pdf, // The **original** filename.
  uri => public://some-dir/some_file.pdf, // The URI to access the actual file.
  filemime => application/pdf,
  filesize => 3067583,
  status => 1,
  timestamp => 1352331360,
);

The FID is a cool thing, because the file_managed table stores the references to files (including all of the info above) and an entity only needs to know the FID in order to join with this table and get all of the file's metadata without reading the file.

To read the contents of the file, you have a few options:

Not sure what you mean explicitly by "read contents", but a literal file_get_contents() would look like this:

$filepath = drupal_realpath($node->field_some_file_field_name['und'][0]['uri']);
$file_contents = file_get_contents($filepath);

If you want to check the MIME or filesize or something like that, you already have that data available to you in the field's array.

If you can elaborate on "reading" the file and what you might like to do before the file field is attached to the node, please update your post and I'll try to update this answer accordingly. There may be another, better place for your work to happen.

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.