Hello,

I have tried to use Plupload integration in my custom module but I couldnt upload file in _submit hook. Is there any example how can I upload images after form submitted.

Best Regards,

Comments

slashrsm’s picture

Files will be uploaded to a temporary location before _submit gets invoked. You should get them in $form_state when execution hits submit function and it is up to you what to do with them.

Sorry for a late reply. Hope it helps.

Romi’s picture

I have tried to create a node and attach a file using plupload. Please guide me in this regard. In $form_state I am getting following array:

[pud] => Array
                (
                    [0] => Array
                        (
                            [tmppath] => temporary://p17es0eqti1sud9jk1k4aj41ja74.tmp
                            [tmpname] => p17es0eqti1sud9jk1k4aj41ja74.tmp
                            [name] => dummy123.pdf
                            [status] => done
                        )

                )
MaudeH’s picture

Hi "Drupalers" and an happy new year !

I've the same problem : what are we doing with this ?
file_save_upload, file_copy, file_move don't save the images (or files) in the public directory...

Thanks for your answers.
Regards,
MaudeH

MaudeH’s picture

Hi,
@Romi : just in case you need some help...

function waip_gallery_create_form_submit($form, &$form_state) {
    $values = $form_state['values'];
    // Prepare the new node
    $node = new stdClass();
    $node->type = 'machine_name'; // The machine name of your content-type
    $node->uid = 0; // The user ID who create the node (0: anomymous | 1: admin)
    $node->created = strtotime('now');
    $node->changed = strtotime('now');
    $node->status = 0; // Is the node published or not ?
    $node->comment = 0;
    $node->promote = 0;
    $node->moderate = 0;
    $node->sticky = 0;
    $node->language = 'und';

    node_object_prepare($node);

    // Add some datas to $node
    $node->title = 'The new node title'; // The title
    $node->field_custom_field1[$node->language][0] = array(
        // A custom field in relation with your form
        'value' => $values['field1'],
        'format' => NULL,
        'safe_value' => $values['field1']
    );

    // Prepare the file to upload
    $filepath = 'public://path/to/your/folder';
    file_prepare_directory($filepath, FILE_CREATE_DIRECTORY); // Create the folder if it doesn't exist

    $files_count = count($values['pud']);
    for ($i = 0; $i < $files_count; $i++) { // For all your files to upload (i use 'pud' from your code above)
        $path = $values['pud'][$i]['tmppath']; // eg: temporary://p17es0eqti1sud9jk1k4aj41ja74.tmp
        $name = $values['pud'][$i]['name']; // eg: dummy123.pdf
        // Set the $file as an object to pass it in the file_copy() function
        $file = (object)array(
            'uid' => 0,
            'uri' => $path,
            'filemime' => file_get_mimetype($path),
            'status' => 1
        );
        // Copy the file using the name attribute, eg: public://path/to/your/folder/dummy123.pdf
        if ($file = file_copy($file, $filepath . '/' . $name)) {
            drupal_set_message('Success');
        }
        else {
            drupal_set_message('Error', 'error');
        }
        // Attach the file as an array to the new node
        $node->field_album_photos[$node->language][$i] = (array)$file;
    }
    // Save the node
    node_save($node);
    // Check if the node is successfully created
    if ($node->nid) {
        drupal_set_message('Node creation: ok');
    }
    else {
        drupal_set_message('Node creation: error', 'error');
    }
}
slashrsm’s picture

Status: Closed (fixed) » Active

The easiest way is to use file_save_upload().

EDIT:
My comment above is not entirely true. Better solution would be file_unmanaged_move(), file_uri_to_object() (part of file_entity but also implemented in plupload.module, so you don't need to install any dependencies) and/or file_move().

slashrsm’s picture

Status: Active » Fixed

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

Status: Active » Closed (fixed)
hargobind’s picture

Here is my code in case it helps anyone:

<?php

/**
 * Form for uploading multiple files.
 */
function mymodule_upload_files_form($form, $form_state) {

  $form['file_upload'] = array(
    '#type' => 'plupload',
    '#title' => t('Upload files'),
    '#autoupload' => FALSE,
    '#autosubmit' => FALSE,
    '#submit_element' => '#edit-submit',
    '#upload_validators' => array(
      'file_validate_extensions' => array('mp3'),
    ),
    '#plupload_settings' => array(
      'runtimes' => 'html5',
      'chunk_size' => '1mb',
    ),
  );


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

  return $form;
}

/**
 * Form validation handler.
 * @see mymodule_upload_files_form().
 */
function mymodule_upload_files_form_validate($form, &$form_state) {
  if (empty($form_state['values']['file_upload'])) {
    form_set_error('file_upload', t('You must select one or more files to upload.'));
    return;
  }
}

/**
 * Form submit handler.
 * @see mymodule_upload_files_form().
 */
function mymodule_upload_files_form_submit($form, &$form_state) {
  $upload_failed = FALSE;

  foreach ($form_state['values']['file_upload'] as $upload) {
    // Move the temporary file into the destination directory.
    $dest_path = file_default_scheme() . '://'; // CHANGE THIS if you want the files to be placed elsewhere.
    $target = $dest_path . '/' . $upload['name'];
    $tmp = plupload_file_uri_to_object($upload['tmppath']);
    // Changing file mime to the proper one.
    $tmp->filemime = file_get_mimetype($target);
    $tmp->status = 0;
    $destination = dirname($target);
    if (!file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
      watchdog('file', 'The upload directory %directory could not be created or is not accessible.', array('%directory' => $destination));
      return FALSE;
    }
    $file = file_move($tmp, $target, FILE_EXISTS_RENAME);
    if (!$file) {
      $upload_failed = TRUE;
      continue;
    }

    // Add file details and make it permanent.
    $file->display = 1;
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    // Inform modules that the file has been moved.
    module_invoke_all('file_move', $file, $tmp);

    // Create an audio node with the new file.
    // DO SOMETHING WITH THE UPLOADED FILES such as attach them to a node.
  }
  
  if (!$upload_failed) {
    // Take the user to the next page.
    drupal_set_message(t('File(s) successfully uploaded.'));
    unset($_GET['destination']);
    $form_state['redirect'] = 'node'; // TAKE THE USER SOMEWHERE ELSE
  }
}
?>