I am currently writing a module that will unzip a .zip file after it has been uploaded. Once this file is unzipped I want to search through it and find certain types of files and create content types that have file or image fields that reference these files, but in order to populate the image and file fields I need to create a file object. How could I do this without having to duplicate the files that have already been uploaded and unzipped?

up vote 15 down vote accepted

I think the easiest way would be to create a file object manually, populate it with the file details, and save it using file_save():

global $user;
$uri = 'public://path/to/file.txt';
$filename = 'file.txt';

$file = new stdClass;
$file->uid = $user->uid;
$file->filename = $filename;
$file->uri = $uri;
$file->filemime = 'text/plain';
$file->filesize = filesize($uri);
$file->status = 1;

file_save($file);

After you've done that you'll probably also want to use the file_usage_add() function to declare a vested interest in the file, so that it doesn't get deleted by any other system process:

$type = 'some_type'; // A string used by your module to identify this type of file entry
$id = 'some_id'; // An identifier used by your module to identify this particular file    

file_usage_add($file, 'MYMODULE', $type, $id);

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.