Drupal 7:上传时重命名文件(通过文件字段) [英] Drupal 7: Rename files on upload (via filefield)
问题描述
我正在寻找一种方法来重命名用户通过文件字段上传的文件.例如,使用 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.
另一种选择是使用 文件(字段)路径,但是:
Another option is to use File (Field) Paths, but:
- 该模块导致我的设置出现警告.
- 为特定目的安装通用模块似乎有点矫枉过正.
推荐答案
您可以通过 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屋!