General developer forum

 
 
Picture of Howard Miller
File API - how do you *move* a file?
Group DevelopersGroup Documentation writersGroup Particularly helpful Moodlers

I have a file stored in a particular file area. How do I move it to a different file area?

The docs talk about moving a file on a particular path but that doesn't really help me. 

 
Average of ratings: -
Davo
Re: File API - how do you *move* a file?
Group DevelopersGroup Particularly helpful Moodlers

Using the $fs->create_file_from_storedfile() function ( https://github.com/moodle/moodle/blob/master/lib/filestorage/file_storage.php#l950 ).

Assuming $file is the file you want to move and $fs is initialised by get_file_storage();

$dest = array('filearea' => 'destination_area'); // You can also include contextid, component, etc. here, if you want to.

$fs->create_file_from_storedfile($dest, $file);

$file->delete();

Due to the efficient storage of the data, the file on  the disk is never actually copied, just a new database record created and the old one deleted.

 
Average of ratings: -
Picture of Howard Miller
Re: File API - how do you *move* a file?
Group DevelopersGroup Documentation writersGroup Particularly helpful Moodlers

Thanks! I actually got there just before you posted. What was tripping me up was that 'create_file_from_storedfile() fails if the destination file already exists. This sounds obvious now but wasn't what I expected and one tends to run the same thing multiple times during testing. 

So... to be on the safe side, an $fs->get_file(...) with the same details as $dest (unfortunately it won't accept the same array -booh) followed by a delete if it succeeds. 

 
Average of ratings: -