没有人能保证自己上传的文件时不会存在相同名字的,那么要如何解决此问题呢,wordpress博客中我们可以利用wp_handle_upload_prefilter来解决此问题,下面演示一个实例.
例,利用图片高与宽生+文件名成名字,代码如下:
- add_filter( 'wp_handle_upload_prefilter', 'modify_uploaded_file_names', 20);
- function modify_uploaded_file_names( $image ) {
- // Get default name of uploaded file and set to variable
- $imagename = $image['name'];
- // Case switch for multiple file extensions
- switch ( $image['type'] ) {
- case 'image/jpeg' :
- $suffix = 'jpg';
- break;
- case 'image/png' :
- $suffix = 'png';
- break;
- case 'image/gif' :
- $suffix = 'gif';
- break;
- }
- // Get size of uploaded image and assign to variable
- $imagesize = getimagesize($image);
- // Re-structure uploaded image name
- $image['name'] = "{$imagesize[0]}x{$imagesize[1]}-{$imagename}.{$suffix}";
- return $image;
- }
例,利用年月日时分秒+千位毫秒整数
以wordpress 3.2.1为例,打开“wp-admin/includes/file.php” www.Vevb.com文件,找到第327行这段代码:
- // Move the file to the uploads dir
- $new_file = $uploads['path'] . "/$filename";
- if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) )
- return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );
将其修改为如下代码:
- // Move the file to the uploads dir
- $new_file = $uploads['path'] . "/".date("YmdHis").floor(microtime()*1000).".".$ext;
- if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) )
- return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );
保存,重新上传文件,这样,新上传的文件,就会自动保存为“年月日时分秒+千位毫秒整数”的新文件名,并保存到相应的年月文件夹之下了.
提醒你,这两种方法个人觉得后者更适合我们一些哦,因为按年月日时分秒+千位毫秒整数不会出现重复名字,而按图片高与宽生+文件名成名字还有可能存在重复名字.
新闻热点
疑难解答
图片精选