It would be convenient than the name of the directory also have the opportunity to set an arbitrary file name. for example, if a book is that the name was: AuthorName - BookTitle.ext

Comments

alan d.’s picture

Title: Filinema parametr for upload_element_save function » Filename parameter for upload_element_save function
Status: Active » Postponed

I'm going to set this as postponed, but will look at reopening it if there is enough demand.

A possible way of extending the function would be: (using the basic example of $node->image)

<?php
  $image_id = 0;
  if($node->image) {

    // returns positive integer if there is a file to handle
    if ($image_id = upload_element_save($node->image, 'dest/directory', FILE_EXISTS_RENAME, 'imagecache_preset')) {

      // only rename new uploads, ignore UPLOAD_ELEMENT_NONE
      if ($node->image->submit_action == UPLOAD_ELEMENT_REPLACE ||
                  $node->image->submit_action == UPLOAD_ELEMENT_NEW) {

        // logic for generating new file name
        $path_parts = pathinfo($node->image->filepath);
        $new_dest = $path_parts['dirname'] .'/'. 'node-'. $node->nid .'.'. $path_parts['extension'];

        // Safeguard against existing files if you use FILE_EXISTS_REPLACE
        // This is not required if you use FILE_EXISTS_RENAME below
        db_query("DELETE FROM {files} WHERE status = 0 AND filepath = '%s'", $new_dest);

        // Do the extra move
        if (file_move($node->image, $new_dest, FILE_EXISTS_RENAME)) {
          // Success, now update the {files} table
          drupal_write_record('files', $node->image, 'fid');
        }
        else {
          watchdog('my_module', 'Failed renaming upload.', WATCHDOG_ERROR);
        }
      }
    }
  }
?>

This would rename to node-123.ext, node-123-1.ext, node-123-2.ext, etc due to FILE_EXISTS_RENAME.

This makes an extra file_copy, but it is probably the easiest method to implement. I haven't run the code, so some debugging may be required.

ipto’s picture

if there is enough demand

I will register a new account and request to ask again and again:)

ipto’s picture

Will the code includes providing an opportunity to specify a file name based on the fields of node the final version, and if so, when can this wait?

alan d.’s picture

Hi Ipto

@see http://drupal.org/node/368002#comment-1235482 for a possible working example.

This should enable you to rename it to anything you like (you may want to pass in the $node if you need this info)

Still not convinced that this is a good feature for general use, especially as this can be one so easily by calling a custom function like the one above.

ipto’s picture

Ok, thank you

alan d.’s picture

Status: Postponed » Closed (won't fix)

Marking closed as I have stopped development with the introduction of the effectively the same element in Drupal 7, (managed_file in the core File module).