Programmatically creating FileField entries

I've had to bump my head into batch uploading files to a drupal installation. Thanks to the prosepoint developers for the fileupload code in their profile. It's code for importing a single file. Just make a simple loop to import bunch of files.

 

<?php
  $mime
= 'audio/mpeg'; // I was importing mp3 files

 
$file_drupal_path "path/under/files/directory/file.mp3";

 
$file = new stdClass();
 
$file->filename = basename($file_drupal_path);
 
$file->filepath = $file_drupal_path;
 
$file->filemime = $mime;
 
$file->filesize = filesize($file_drupal_path);

 
$file->uid = $uid;
 
$file->status = FILE_STATUS_PERMANENT;
 
$file->timestamp = time();
 
drupal_write_record('files', $file);


 
$node = new StdClass();
 
$node->type = 'word';
 
$node->body = $body;
 
$node->title = $word;
 
$node->field_pronounciation = array(
    array(
     
'fid' => $file->fid,
     
'title' => basename($file->filename),
     
'filename' => $file->filename,
     
'filepath' => $file->filepath,
     
'filesize' => $file->filesize,
     
'mimetype' => $mime,
     
'description' => basename($file->filename),
     
'list' => 1,
    ),
  );
 
$node->uid = 1;
 
$node->status = 1;
 
$node->active = 1;
 
$node->promote = 1;
 
node_save($node);
?>

Other solutions for lazy coders/non-coders

A more elaborate way of importing large amounts of files using batch API can be found in #292904: Mass import/upload?.

FeedAPI

FeedAPI is first and foremost intended to import feeds from external sites, but it can just as well be used to import a static XML file of your choosing from a local server.

By exteding FeedAPI with Feed Element Mapper and using one of the mappers in one of these issues:

#319538: Mapper for FileField / ImageField
#535970: Mapper for imagefield
#224235: Mapper for CCK Image Field

you might be able to have it create nodes from your custom xml.

FeedAPI is supposed to be replaced by Feeds.

Feeds

If you have tried out the Feeds module, then chip in with your 2 cents here. Feeds is supposed to replace FeedAPI, but I don't know how well it is working, nor if it has the same number of modules extending its functionality as FeedAPI has.

Node Import

Node Import can import nodes from CSV/TSV files. It says that CCK filefield and imagefield content may be supported.

I haven't tried it since before I started this book page, because at that time it didn't fullfill my needs.

Further solutions

I haven't browsed the Import/Export projects in depth, you might find a better fit for your needs there.

文章分类: 
文章标签: