Raza Mehdi's Blog

How to create Filefield Entries in Drupal?

by on Jan.06, 2011, under Drupal

Hey guys! I wrote a tutorial on how to programmatically create nodes in Drupal. In this tutorial, i will show you how to write FileField entries using a Drupal module.

function YOURMODULE_CALLBACK() {

	$arrfiles = return filePaths(YOUR_IMAGES_DIRPATH);

	$filesinfo = array();

	foreach($arrfiles as $file) {

		$fn = basename($file);

		//copying from source folder to drupal's sites/default/files

		$cp = copy($file,'/sites/default/files'.$fn);

		if($cp) {
			$files = new stdClass();
			$files->filename = basename($file);
			$files->filepath = 'sites/default/files'.$fn;
			$files->filemime = file_get_mimetype(basename($file));
			$files->filesize = filesize($file);
			$files->uid = 1;
			$files->status = FILE_STATUS_PERMANENT;
			$files->timestamp = time();

			drupal_write_record('files', $files);

			$filesinfo[] = array(
				'fid' => $files->fid,
				'title' => basename($files->filename),
				'filename' => $files->filename,
				'filepath' => $files->filepath,
				'filesize' => $files->filesize,
				'mimetype' => file_get_mimetype(basename($file)),
				'description' => basename($file),
				'list' => 1,
			);
		}
	}

	$node = node_load(NODEID);

	$node->field_images = $filesinfo;

	node_save($node);

}

function filePaths($path) {

	$dir = new DirectoryIterator($path);
	$filelist = array();

	foreach($dir as $file) {
		if($file->isFile()) {
			$filelist[] = $file->getFilename();

		}

		if($file->isDir()) {
			filePaths($file->getPath());
		}
	}
	return $filelist;
}
Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks

  • Huunq

    Thank you. You’re my savior :)

  • Raza

    Hey Huunq!

    You are welcome :)

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!