update a file programmatically with file api?

update a file programmatically with file api?

by A Guy -
Number of replies: 3

Good evening,

I have a plugin that presents a filemanager for the user to upload a file. I store it. All works as desired. I can even retrieve it.


I do retrieve and write it to disk for various things to be done to it. But after all of this work I want to upload the modified version back to mdl_files overwriting the existing file--the one I just downloaded.

I've tried $fs->create_file_from_pathname but of course like the footnote in the documentation states (although a little confusingly) you have to delete the original file first before you can do this one. It will work. But it updates/changes the file id which causes me issues for various reasons.

So I tried replace_file_with() on the file I download. Doesn't work as the file has to be a "stored file".


So is there really no way to programmatically download a stored file, change the contents, and write it back, overwriting what was there already without changing the file id?


Thank you.

Average of ratings: Useful (1)
In reply to A Guy

Re: update a file programmatically with file api?

by Justin Hunt -
Picture of Particularly helpful Moodlers Picture of Plugin developers

From Poodll code ....this works ..not sure how well it fits with your use case though ..

$newfile = $fs->create_file_from_pathname($draftfilerecord, $newfilepath);
$permanentfile = $fs->get_file_by_id($permfilerecord->id);
$permanentfile->replace_file_with($newfile);

Average of ratings: Useful (1)
In reply to Justin Hunt

Re: update a file programmatically with file api?

by A Guy -

Ah. Makes sense. Thanks

In reply to Justin Hunt

Re: update a file programmatically with file api?

by John Doyle -

Really helpful - thanks to you both. Ended up needing similar approach for dynamically updating certain course files - the tip here definitely reduced time to get it going.

Use case on this end required updating an existing file based on new/temporary JSON data. Was able to use 

$fs->create_file_from_string 

to store the new data, and after confirming update of the old/existing file, deleted newfile with 

$newfile->delete();

Hope sharing this is helpful for others with similar requirements.