dpo15099
2019-06-06 21:20
浏览 119
已采纳

使用自定义文件名在WordPress上传文件

I'm currently developing a plugin for my page. The goal is to upload a custom profile image from a user page. Now I want to store each image under a pre-defined name. Sadly I've no plan how I can set a custom name for a file during the file upload with the WordPress function wp_upload_bits():

$filename =  $_FILES['file']['name'];

$uploaded_bits = wp_upload_bits(
    $filename,
    null,
    file_get_contents( $_FILES['file']['tmp_name'] )
);

Currently when I upload for example an image with the name yolo.png, the name stays yolo.png.

Now I want to define the new name this way:

$filename = 'profile-image-' . get_current_user_id();

But this can't work because the $_FILES['file']['name'] is the temporarily saved file on my server and this is yolo.png. So do you have any idea how I can reach my goal?

图片转代码服务由CSDN问答提供 功能建议

我正在为我的页面开发一个插件。 目标是从用户页面上传自定义配置文件图像。 现在我想以预定义的名称存储每个图像。 遗憾的是,我没有计划如何在文件上传期间使用WordPress函数 wp_upload_bits()设置文件的自定义名称:

  $  filename = $ _FILES ['file'] ['name']; 
 
 $ uploaded_bits = wp_upload_bits(
 $ filename,
 null,
 file_get_contents($ _FILES ['file'] ['tmp_name'])  
); 
   
 
 

目前,当我上传例如名称为 yolo.png 的图片时,名称仍为 yolo .PNG

现在我想用这种方式定义新名称:

  $ filename ='profile-image-'。  get_current_user_id(); 
   
 
 

但这不起作用,因为 $ _ FILES ['file'] ['name'] 是 暂时保存在我的服务器上的文件,这是 yolo.png 。 所以你知道我如何达到我的目标吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doutinghou6980 2019-06-06 22:00
    已采纳

    Today I'm not that smart. I need to pass the file type, otherwise the upload can't work...:

    $filename = 'profile-image-' . get_current_user_id() . '.' . substr( strrchr( $_FILES['file']['name'], '.' ), 1 );
    

    With this part of code I just get the file extension:

    '.' . substr( strrchr( $_FILES['file']['name'], '.' ), 1 );
    
    已采纳该答案
    打赏 评论
  • duandang6352 2019-06-06 22:05

    you can get the file extension also by splitting the string

    $arr = explode('.',$_FILES['file']['name']);
    $ext = end($arr);
    

    you then concatenate the file extension with the name you want.

    you could also try to the function

    move_uploaded_file($_FILES['file']['tmp_name'], 'path/to/folder/'.$filename);
    
    打赏 评论

相关推荐 更多相似问题