Please Note: We are no longer using forums to facilitate standard support. All support issues will be handled via email using our support ticket system. For more detailed information on this change, please see this blog post.

Renaming uploaded files before saving

  1. Since gravityforms doesnt rename files with special hyphenated characters, these are saved in the filesystem with wrong encoding thus resulting different filenames in the filesystem and in the database. I have tried to rename the $_FILES[n]['name'] but it does not alters the saved filename for some reason.

    Any ideas?

    Posted 5 years ago on Wednesday January 13, 2010 | Permalink
  2. Renaming uploaded files has come up quite a few times and we will probably add that feature on a future version

    Since $_FILES[...] is readonly and you won't be able to rename it, what you will have to do is rename the file after it has been uploaded using the post submit hook.

    We have had another user that used the following code snippet to rename uploaded files so that they match the entry id.
    You will need to replace 18 (in $form["id"] != 18) with your actual form id and 2 (in $original_file_url = $entry[2];) with your file upload field id.
    Place it in your theme's functions.php.
    Let me know how it goes.

    add_action("gform_post_submission", "rename_file", 10, 2);
    function rename_file($entry, $form){
    
        //ignore requests from forms other than ID 18
        if($form["id"] != 18)
            return;
    
        $upload_info = wp_upload_dir();
    
        //original name/path
        $original_file_url = $entry[2];
        $original_file_path = str_replace($upload_info["baseurl"], $upload_info["basedir"], $original_file_url);
        $original_file_info = pathinfo($original_file_url);
    
        //New File Name (without extension).
        //NOTE: Change this line to create the filename you would like to have
        $new_name = $entry["id"];
    
        //adding same extension as original
        $new_name .= "." . $original_file_info["extension"];
    
        $new_file_url = str_replace($original_file_info["basename"], $new_name, $original_file_url);
        $new_file_path = str_replace($original_file_info["basename"], $new_name, $original_file_path);
    
        //rename file
        $is_success = rename($original_file_path, $new_file_path);
    
        //if file was renamed successfully, updating entry so that it points to the new file
        if($is_success){
            global $wpdb;
            $wpdb->update(RGFormsModel::get_lead_details_table_name(), array("value" => $new_file_url), array("lead_id" => $entry["id"], "value" => $original_file_url));
        }
    }
    Posted 5 years ago on Wednesday January 13, 2010 | Permalink
  3. Thanks for your reply, this solution is pretty much a workaround only, and does not works about unexpected encoding results on the filesystem. So we will simply rename the file to the user id, which works fine, but it seems only for the case with one file upload field. What if i have multiple uploads in the same form?

    Posted 5 years ago on Wednesday January 13, 2010 | Permalink
  4. Yes, I agree with you. This is a workaround, but unfortunately it is best we can do without changing the core files. Like I said, we will be adding the ability for the uploaded file to be renamed in a future version and that will be real solution.

    For multiple file upload fields, try the following.

    add_action("gform_post_submission", "rename_fileuploads", 10, 2);
    function rename_fileuploads($entry, $form){
    
        //ignore requests from forms other than ID 18
        if($form["id"] != 18)
            return;
    
        rename_file($entry, $form, 8); //renaming file upload id=8
        rename_file($entry, $form, 9); //renaming file upload id=9
    }
    
    function rename_file($entry, $form, $field_id){
       $upload_info = wp_upload_dir();
    
        //original name/path
        $original_file_url = $entry[$field_id];
        $original_file_path = str_replace($upload_info["baseurl"], $upload_info["basedir"], $original_file_url);
        $original_file_info = pathinfo($original_file_url);
    
        //New File Name (without extension).
        //NOTE: Change this line to create the filename you would like to have
        $new_name = $entry["id"] . "_" . $field_id;
    
        //adding same extension as original
        $new_name .= "." . $original_file_info["extension"];
    
        $new_file_url = str_replace($original_file_info["basename"], $new_name, $original_file_url);
        $new_file_path = str_replace($original_file_info["basename"], $new_name, $original_file_path);
    
        //rename file
        $is_success = rename($original_file_path, $new_file_path);
    
        //if file was renamed successfully, updating entry so that it points to the new file
        if($is_success){
            global $wpdb;
            $wpdb->update(RGFormsModel::get_lead_details_table_name(), array("value" => $new_file_url), array("lead_id" => $entry["id"], "value" => $original_file_url));
        }
    }

    If your encoding issue prevents you from using this solution, let me know and we will see what could be done.

    Posted 5 years ago on Wednesday January 13, 2010 | Permalink
  5. Great, thanks!

    Posted 5 years ago on Thursday January 14, 2010 | Permalink
  6. pagedmedia
    Member

    I tried this solution for a form that I am working on, and it is not working for me. :(

    Posted 4 years ago on Friday July 23, 2010 | Permalink
  7. pagedmedia
    Member

    This is the link: http://whrwa.com/emily/coordinators-only/ (password: bunnyfoofoo)

    I just want to rename the file to entry name and, if possible, the entry id - can that be pulled up?

    Posted 4 years ago on Friday July 23, 2010 | Permalink
  8. Try the following code. Place it in your theme's function.php file.

    add_action("gform_post_submission", "rename_file", 10, 2);
    function rename_file($entry, $form){
    
        //---------------------------------------------------------
        //---------------------------------------------------------
        //REPLACE THESE THREE VARIABLES BASED ON YOUR ACTUAL IDs
        $form_id = "6";
        $fileupload_field_id = "43";
        $name_field_id = "41";
        //---------------------------------------------------------
        //---------------------------------------------------------
    
        //ignore other forms
        if($form["id"] != $form_id)
            return;
    
        $upload_info = wp_upload_dir();
    
        //original name/path
        $original_file_url = $entry[$fileupload_field_id];
        $original_file_path = str_replace($upload_info["baseurl"], $upload_info["basedir"], $original_file_url);
        $original_file_info = pathinfo($original_file_url);
    
        //New File Name (without extension).
        $new_name = $entry[$name_field_id] . "_" . $entry["id"];
    
        //adding same extension as original
        $new_name .= "." . $original_file_info["extension"];
    
        $new_file_url = str_replace($original_file_info["basename"], $new_name, $original_file_url);
        $new_file_path = str_replace($original_file_info["basename"], $new_name, $original_file_path);
    
        //rename file
        $is_success = rename($original_file_path, $new_file_path);
    
        //if file was renamed successfully, updating entry so that it points to the new file
        if($is_success){
            global $wpdb;
            $wpdb->update(RGFormsModel::get_lead_details_table_name(), array("value" => $new_file_url), array("lead_id" => $entry["id"], "value" => $original_file_url));
        }
    }
    Posted 4 years ago on Monday July 26, 2010 | Permalink
  9. pagedmedia
    Member

    Thanks!

    Posted 4 years ago on Tuesday August 10, 2010 | Permalink
  10. pagedmedia
    Member

    hummm... *wonders if it would work as a prehook...*

    Posted 4 years ago on Tuesday August 10, 2010 | Permalink
  11. alpersari
    Member

    Hi,
    I've tried to rename while uploading by using first function you submitted. But it doesn't work for me. I'm using Xampp for windows.

    Posted 4 years ago on Tuesday January 4, 2011 | Permalink
  12. charger15
    Member

    @Alex Cancado:

    I'm using your function above (the one with multiple file upload fields) to rename the uploaded files – works like a charm. The files get renamed and the DB fields are updated.
    I now made a function that takes the custom field values of the file upload fields and adds them as attachments so that I can see them in the media library. It looks like that:

    add_action("gform_post_submission", "usr_custom_fields_to_attachment", 10, 2);
    function usr_custom_fields_to_attachment($entry, $form){
    
      //ignore requests from forms other than ID 1
      if($form['id'] != 1)
        return;
    
      //getting post
      $post = get_post($entry['post_id']);
    
      // add uploaded files as post attachment
      $file_values = get_post_custom_values('file_upload', $post->ID);
      foreach($file_values as $value) {
        if($value != ''){
          //update post meta with absolute path (needed for wp_insert_attachment)
          $abspath = $_SERVER['DOCUMENT_ROOT'] . wp_make_link_relative($value);
          update_post_meta($post->ID, 'file_upload', $abspath, $value);
          //check file type
          $wp_filetype = wp_check_filetype(basename($abspath), null );
          //create attachment object
          $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title' => preg_replace('/\.[^.]+$/', '', basename($abspath)),
            'post_content' => '',
            'post_status' => 'inherit'
          );
          //insert attachment and process attached file
          $attach_id = wp_insert_attachment($attachment, $abspath, $post->ID);
          require_once(ABSPATH . 'wp-admin/includes/image.php');
          $attach_data = wp_generate_attachment_metadata($attach_id, $abspath);
          wp_update_attachment_metadata($attach_id, $attach_data);
        }
      }
    }

    My problem now is: When I use your function, the custom fields won't get updated (only the DB), so in there is still the link with the old file name. My function then processes the outdated custom fields and of course can't find the image. I'm unable to see how I can update the metadata inside your function or to get the updated fields directly out of the DB and use them inside my function. Any help?

    I set up the fields in your function like that (The last added parameter in usr_rename_file is only used for the new filename):

    add_action("gform_post_submission", "usr_rename_fileuploads", 10, 2);
    function usr_rename_fileuploads($entry, $form){
    
        //ignore requests from forms other than ID 1
        if($form["id"] != 1)
            return;
    
        usr_rename_file($entry, $form, 28, 1); //renaming file upload field 1 id=28
        usr_rename_file($entry, $form, 29, 2); //renaming file upload field 2 id=29
        usr_rename_file($entry, $form, 30, 3); //renaming file upload field 3 id=30
    }

    Another little question on top: If the user doesn't upload a second or third file, Gravity Form anyway creates the custom field but without value. How can I avoid this behavior?

    Thanks!

    Posted 3 years ago on Saturday August 27, 2011 | Permalink
  13. charger15
    Member

    just found the solution. i added the following line of code after the $wpdb->update

    update_post_meta($entry["post_id"], 'file_upload', $new_file_url, $original_file_url);

    however i still don't know how to avoid empty fields to be inserted as custom fields with empty value.

    Posted 3 years ago on Thursday September 1, 2011 | Permalink
  14. Check to see if the value is empty before inserting it. Which line of code does the insert, and what value will be empty when you don't want to create an empty custom field? I'm not sure which line in the code above does that. If you can point to the code, we can help you figure out how to avoid inserting an empty value.

    Posted 3 years ago on Thursday September 1, 2011 | Permalink
  15. Has the ability to rename uploaded files been implemented yet?

    Posted 3 years ago on Wednesday November 30, 2011 | Permalink
  16. While there is a hook to customize the upload path, and the file permission, there currently is not a hook to customize the uploaded file name. I will discuss this with our lead developer tomorrow and see if this is something we can get added to the 1.6.2 release which is getting ready to be pushed live.

    Posted 3 years ago on Wednesday November 30, 2011 | Permalink
  17. Chineseand
    Member

    Any update on this? Could there be the admin option to make the "pretty filename" field mandatory?

    Posted 3 years ago on Sunday February 5, 2012 | Permalink
  18. @Chineseand We haven't yet added a hook that can be used to rename the file that is uploaded. Currently it is only possible to rename the directory. We do handle storing the filename properly if it has special characters by using built in WordPress filename sanitization functionality.

    As for your question regarding an admin option, I'm not exactly sure what you are referring to as far as making the "pretty filename" field mandatory. I don't know what "pretty filename" you are talking about. Can you clarify?

    Posted 3 years ago on Monday February 13, 2012 | Permalink
  19. Chineseand
    Member

    Hi Carl,
    Yeah, sorry for the confusion. I was referring to the as-yet non-existent functionality to give a title to the filename..

    Is there a function within the system already that would allow writing the filename, and not the url? Something like this:
    <div id="uploadedfile3"><a href="{File 3:11:full:url}" target="_blank">{File 3:11:filename}</a></div>
    Currently, I use this:
    <div id="uploadedfile3"><a href="{File 3:11:full:url}" target="_blank">{File 3:11}</a></div>
    but it is outputting the full url to the attachment instead of the filename only.

    Thanks again for your help. These support forums have been great.

    Posted 3 years ago on Monday February 13, 2012 | Permalink
  20. Currently there is no merge tag option to only output the filename of an uploaded file. The way the file upload field works is the full path URL to the file that is uploaded is what is stored as the value in the database. We can see about adding this feature in the future as a merge tag option for the File Upload field but it is not currently a feature.

    As for the ability to control the filename, it would be added as an available hook. It would not be added to the form editor UI itself. It would only exist as a hook for developers to use to implement a customization. This is because it's a feature that the majority of users would not use or need so therefore it's better suited as a hook rather than adding it to the UI.

    Posted 3 years ago on Monday February 13, 2012 | Permalink

This topic has been resolved and has been closed to new replies.

Support Tickets

Open A New Support Ticket
 Open A New Priority Support Ticket *

* Developer license holders only