2

I am working on a module and I am trying to add an upload box for an MP3 file. I cannot seem to get it working no matter what I try to do. I have looked at file_save_upload and I am not having any luck. Below is my form code. Could someone point me in the right direction for the file upload process?

$form['background_audio_file'] = array(
  '#type'=> 'file',
  '#title' => t('Upload File'),
  '#description' => t('Please select your file to be uploaded'),
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Save Changes'),
);

The form is working great I just cant seem to find a good example and makes sense for uploading a simple mp3 file. This is D7 btw.

Thanks in advance.

Justin

1 Answer 1

3

Rather than worry about moving/saving the file yourself you could use the managed_file element type and let Drupal do it for you:

function mymodule_some_form($form, &$form_state) {
  $form['background_audio_file'] = array(
    '#type' => 'managed_file',
    '#title' => t('Upload File'),
    '#description' => t('Please select your file to be uploaded'),
    '#upload_location' => 'public://audio-files' 
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save Changes'),
  );

  return $form;
}

function mymodule_some_form_submit($form, &$form_state) {
  // The file is automatically uploaded and saved in the default
  // validation process so you just need to load the file object at this point,
  // mark that you want to keep it, and save it again.
  // The file ID is contained in the $form_state['values'] array
  $file = file_load($form_state['values']['background_audio_file']);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
}

Uploading files using this method has the added benefit of a reference to them being added to the file_managed table so they can be managed with the system at a later date if needs be.

Hope that helps.

3
  • Yes that does help! Thank you! I have implimented the code you provided and I get this error when I try to upload a file: Notice: Undefined property: stdClass::$uri in file_save() (line 573 of /Users/jtharpe/Overflow_Dev/includes/file.inc).
    – Justin
    Commented Feb 17, 2012 at 23:15
  • Never mind I figured that part above up however after uploading my file I get the error: Only files with the following extensions are allowed: jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp. <-- Is there a way to add MP3 to this so I can upload my file?'
    – Justin
    Commented Feb 17, 2012 at 23:22
  • There is, see this post for more details
    – Clive
    Commented Feb 18, 2012 at 10:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.