Skip to main content

Drupal Form Uploads

Posted in

I spent way too long tonight trying to figure out how to upload a file to drupal, using the "file" field type in drupal. It's really easy, though, once you figure it out.

First, to instantiate the field:

<?php
function my_form() {
 
 
$form = array();
 
$form['#attributes'] = array('enctype' => 'multipart/form-data');
 
 
$form['upload'] = array(
   
'#type' => 'file',
   
'#title' => t('File to upload'),
  );
 
 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => 'Upload',
  );
  return
$form;
}
?>

Then, to grab it:

<?php
function myform_submit($form, &$form_state) {
 
upload_node_form_submit(&$form, &$form_state);
 
$file_node = $form['#node'];
 
$files = $file_node->files;
  foreach (
$files as $key => $value) {
   
$file = $value;
   
$filename = $file->filename;
   
drupal_set_message(t("Received file $filename"));
    foreach(
$file as $key => $value) {
     
drupal_set_message(t("Attribute $key : $value"));
    }
   
  }
}
?>

Trackback URL for this post:

http://www.euphline.com/trackback/140