Drupal 7:在上载时重命名文件(通过文件夹) [英] Drupal 7: Rename files on upload (via filefield)

查看:307
本文介绍了Drupal 7:在上载时重命名文件(通过文件夹)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方式来重命名用户通过文件夹上传的文件。例如,使用 uniqid 重命名用户个人资料照片。

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.

我在 Drupal 6:如何更改文件名上传,但找不到D7的任何东西。

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

另一个选项是使用 File(Field)Paths ,but:

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



  1. 似乎是为了特别的目的而安装一个通用模块有点过分。


推荐答案

您可以通过 hook_file_presave 作为您的需求模式
作为示例

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'];
}

但这种方法不会重命名filname(它只是重命名文件名在file_managed表中)如果您还要重命名文件名(文件uri),您应该使用以下代码

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);
}

这篇关于Drupal 7:在上载时重命名文件(通过文件夹)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆