dpo15099
2019-06-06 21:20 阅读 104
已采纳

使用自定义文件名在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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    doutinghou6980 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 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);
    
    点赞 评论 复制链接分享

相关推荐