Drupal 7: Rename files on upload (via filefield)

半腔热情 提交于 2020-01-13 14:54:10

问题


I am looking for a way to rename files that are uploaded by users through a filefield. For example, rename user profile photos using uniqid.

I found a good solution for D6 at "Drupal 6: How to Change Filename on Upload" but can't find anything for D7.

Another option is to use File (Field) Paths, but:

  1. The module causes warnings on my setup.
  2. Seems to be a bit of an overkill to install a general module for a very specific purpose.

回答1:


You can change every file upload by hook_file_presave as your desire pattern as example

function yourmodulename_file_presave($file) {
  $parts = pathinfo($file->filename);
  $file->filename = 'mypattern_'.$file->uid .'_'. $file->timestamp . '.' . $parts['extension'];
}

but this method do not rename filname(it just rename file name in file_managed table), if you want also rename file name (uri of file) you should use below code

function hook_file_insert($file) {
  $parts = pathinfo($file->filename);
  $uri = 'public://'.'mypattern_'.$file->uid .'_'. $file->timestamp . '.' . $parts['extension'];
  $file=file_move($file, $uri);
}



回答2:


Important part is the replacement of SOMEFILENAME

function MYMODULE_background_form_validate($form, &$form_state) {
  $file = file_save_upload('file', array(
      'file_validate_is_image' => array(),
      'file_validate_extensions' => array('jpg'),
  ));
  if ($file) {
    if ($file = file_move($file, 'public://**SOMEFILENAME**', FILE_EXISTS_REPLACE)) {
      $form_state['values']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }
  else {
    form_set_error('file', t('No file was uploaded.'));
  }
}

function MYMODULE_background_form_submit(&$form, &$form_state) {
  $file=$form_state['values']['file'];
  unset($form_state['values']['file']);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  drupal_set_message(t('Thanks, the background has been saved.'));
}


来源:https://stackoverflow.com/questions/13903458/drupal-7-rename-files-on-upload-via-filefield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!