phpdrupaldrupal-6

How can I associate many existing files with drupal filefield?


I have many mp3 files stored on my server already from a static website, and we're now moving to drupal. I'm going to create a node for each audio file, but I don't want to have to upload each file again. I'd rather copy the files into the drupal files directory where I want them, and then associate the nodes with the appropriate file.

Any ideas on how to accomplish that?

Thanks!


Solution

  • I am not sure if I am going to propose a different approach or if I am about to tell with different words what you already meant with your original question, but as you want the nodes to be the files, I would rather generate the nodes starting from the files, rather than associating existing nodes with existing files.

    In generic terms I would do it programmatically: for each existing files in your import directory I would build the $node object and then invoke node_save($node) to store it in Drupal.

    Of course in building the $node object you will need to invoke the API function of the module you are using to manage the files. Here's some sample code I wrote to do a similar task. In this scenario I was attaching a product sheet to a product (a node with additional fields), so...

    So the example:

    // Load the CCK field
    $field = content_fields('field_sheet', 'product');
    // Load the appropriate validators
    $validators = array_merge(filefield_widget_upload_validators($field));
    // Where do we store the files?
    $files_path = filefield_widget_file_path($field);
    // Create the file object
    $file = field_file_save_file($sheet_file, $validators, $files_path);
    // Apply the file to the field, this sets the first file only, could be looped
    // if there were more files
    $node->field_scheda = array(0 => $file);
    // The file has been copied in the appropriate directory, so it can be
    // removed from the import directory
    unlink($sheet_file);
    

    BTW: if you use a library to read MP3 metadata, you could set $node->title and other attributes in a sensible way.

    Hope this helps!