I've been unsuccessful in tracking down any in depth resources on file handling in Drupal 5.x.

The module I'm working on has custom forms and I wish to allow users to attach an arbitrary number of files that will be saved to the server using Drupal's built in file handling along with the rest of the form data. I've read through the api.drupal.org information on File Interface functions, but can't seem to piece it all together. I also have the Pro Drupal Development book, but its chapter on "Working with Files" is all of 7 pages long and nearly useless from a developer standpoint.

Are there any good tutorials on how to go about file upload(s) in custom forms? Any resources would be welcome, though a nice walk through example would be ideal if one already exists.

Thanks!

Comments

cbovard’s picture

subscribing

www.chrisbovard.com | Drupal Developer / Themer

gregrenner’s picture

subscribing

xgretsch’s picture

Here's how a bare bones version of the Drupal file upload API seems to work. You'll need something a lot more complicated if you want to use multipart forms, do lists of files, editing, etc, but this seems to work for a starter (developed by trial and error and inspection of a lot of stuff with Firebug - I couldn't find any documents either).

Step 1: include a file element in your form, such as:

function myexampleform($form_values){
  $form=array();
  ...
  $form["examplekey"]=array(
    "#type"=>"file",
    "#title"=>t("Upload something I need for this example"),
    "#default_value"=>$form_values["examplekey"],
  …
  return $form;
);

Step 2: in your validation function, retrieve the file. You can now do stuff with it using the APIs to be found on http://api.drupal.org/api/group/file/5

function myexampleform_validate($form_id,$form_values){
  …
  $file=file_check_upload("examplekey");
  if(!$file){
    form_set_error("","Please choose a file to upload");
    return;
  }
  // At this point, you can put some processing on your file to see if you like it, and 
  // do a form_set_error if anything's wrong with it.
  …
}

Step 3: in your submit function, store the file away somewhere.

function myexampleform_submit($form_id,$form_values){
  ...
  // We'll use the default "files" directory as the destination, but we could choose
  // somewhere else if we wanted to
  $finfo=file_save_upload("examplekey",file_directory_path(),FILE_EXISTS_RENAME);
  if($finfo==0){
    // Take some error action
    watchdog("My application","It all went horribly wrong",WATCHDOG_ERROR);
  ...
  }
...
}

I hope this helps someone!

David

kenorb’s picture

Thanks, it's very useful example.
http://api.drupal.org/api/function/file_check_upload/5
In Drupal 6, this has been renamed to file_save_upload()

nmontec’s picture

I can't find a drupal 7 version for this that could work. Any help?