沒有人能保證自己上傳的文件時不會存在相同名字的,那么要如何解決此問題呢,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.49028c.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'] ) );
保存,重新上傳文件,這樣,新上傳的文件,就會自動保存為“年月日時分秒+千位毫秒整數”的新文件名,并保存到相應的年月文件夾之下了.
提醒你,這兩種方法個人覺得后者更適合我們一些哦,因為按年月日時分秒+千位毫秒整數不會出現重復名字,而按圖片高與寬生+文件名成名字還有可能存在重復名字.
新聞熱點
疑難解答
圖片精選