File upload hook – how to integrate existing file manipulation code into Drupal

I want to create a waveform image for every mp3 file I upload in a Drupal 7 website (as admin), and store it as a png for display in the frontend. I can use this script in order to do that.

I want to know what is the Drupal way of integrating that script, specifically:

  1. I guess that functionality will go into a module; where should I hook? file upload (there will be more than one file types to upload, and I would just want to work on the mp3)?
  2. how should I save the resulting waveform picture (where in the filesystem and how would I attach it as a field to my custom node type)?

As I’m new to Drupal (but experienced with PHP), I would appreciate a detailed response, but if you know of a module that already does that – I couldn’t find it – that would be the shortest answer possible. 🙂

 

Add Comment



  • 1 Answer(s)

    try this code

    function mymodule_node_presave($node) {
    
    //drupal_set_message('<pre>'.var_export($node, TRUE).'</pre>');
    
    if (!isset($node->field_pic['und'][0]) && isset($node->field_file['und'][0]['fid'])) {
    
    $result = db_query("SELECT filename, uri, filemime FROM {file_managed} WHERE fid = :fid",
    
    array(':fid' => $node->field_file['und'][0]['fid']));
    
    $record = $result->fetchObject();
    
    if ($record->filemime == 'audio/mpeg' && pathinfo($record->filename, PATHINFO_EXTENSION) == 'mp3') {
    
    // TODO - create the picture, save in the temporary files folder and return the filename.
    
    $filename = 'created_image.png';
    
    $image = file_get_contents('sites/default/files/tmp/'.$filename);
    
    // public://pics/ -> sites/default/files/pics
    
    $file = file_save_data($image, 'public://pics/'.$filename, FILE_EXISTS_RENAME);
    
    drupal_unlink('sites/default/files/tmp/'.$filename);
    
    $node->field_pic['und'][0] = (array) $file;
    
    }
    
    }
    
    }
    
    
    Answered on July 19, 2017.
    Add Comment



  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.