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?

up vote 3 down vote accepted

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
file_save($file);

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 acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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