I have a content type that contains a file field which is always a .zip file. When a file is uploaded I have a module that unzips the file to make a few changes then re zips the file to a new location. I would like to associate this newly created .zip file with my content type but so far I have not been able to find a way to do that. I initially tried to change the url of the file field in which it worked temporarily but it seems that the file field was later re-saved with the initial value.

I do my unzipping and re-zipped from hook_node_presave (I also tried to do from hook_node_insert) but neither seemed to work. Could anyone offer me any advice about how to change the file of a file field?

1 Answer 1


File fields are referenced by their ID in the file_managed table; as well as updating the field in your presave hook, you'll probably need to update the file entity that relates to that id with the new filename/path.

This is just a basic example but it should give you a starting point:

// Get the file id from the field
$fid = $node->field_file[$node->language][0]['fid'];

// Load the file
$file = file_load($fid);

// Update the filename
$file->filename = basename($new_path);

// Update the uri (this must be in the format of a schema uri, e.g. public://folder/file.jpg
$file->uri = $new_path;

// Save the changes

You might also want to update the filesize field; it's used in a few places in the system.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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