How to Import Files into Drupal CCK Fields

At last night's Ann Arbor Drupal Meetup, a question was raised about how to write an import script to create Drupal nodes that include a Filefield CCK field. Filefields and Imagefields present a particular problem for import because the file must be stored into the Drupal files table before you can save them to the node. In the discussion that followed, it seemed that several of us at the meeting had developed our own ways to do this in the past for various reasons. So, I thought I would post a couple solutions for others who need to do this.

Option 1: Read the Manual

There is a manual page that explains how to programmatically import files to Filefield. However, like many Drupal manual pages, if you read through the comments, there are about 20 different versions of the code, and the discussion is often difficult for novice users to follow. The code on this page does work, but there is something simpler that we ended up with at the meeting.

Option 2: Use a Helper Function

The Filefield module has a helper function called field_file_save_file() that does a lot of the work for you. To use the function, you just need to give the original file path and a destination path if you want the file copied into a new location. Here's a simple example of a script that creates a story node and imports an image file into the "field_image" CCK field. (The file importing lines are highlighted.)

 
<?php

$node = new StdClass();
$node->type = 'story';
$node->body = 'Testing.';
$node->title = 'Testing';

$file = field_file_save_file('import-images/buzz2.jpg', array(), 'sites/default/files/images');
$node->field_image = array($file);

$node->uid = 1;
$node->status = 1;
node_save($node);

This script can't be run on the command line without some other include lines to bootstrap the Drupal system. However, if you use Drush (and you should be using Drush), you don't need to do anything extra. Just run "drush scr import.php". That's it. Adding those two lines to your import script is all need to do to import files to Filefield CCK fields. Easy to do now that you know.

If you have any questions or problems using the method above, leave a comment below, and I'll see if I can help you out.

Wayne Eaker
November 30, 2010