Renaming an uploaded file in CodeIgniter

2020-02-10 04:32发布

Using CodeIgniter, I am trying to modify the name of the uploaded file to camelCase by removing any spaces and capitalizing subsequent words.

I am pretty sure that I can rename the file using the second parameter of move_uploaded_file but I don't even know where to look to figure out how to modify the name to camelCase.

Thanks in advance! Jon

标签: codeigniter
3条回答
Animai°情兽
2楼-- · 2020-02-10 05:16

Check out CI's upload library:

http://www.codeigniter.com/user_guide/libraries/file_uploading.html

Let's first take a look at how to do a simple file upload without changing the filename:

$config['upload_path']   = './uploads/';
$config['allowed_types'] = 'jpg|jpeg|gif|png';

$this->upload->initialize($config);

if ( ! $this->upload->do_upload())
{
    $error = $this->upload->display_errors();
}   
else
{
    $file_data = $this->upload->data();
}

It's that simple and it works quite well.

Now, let's take a look at the meat of your problem. First we need to get the file name from the $_FILES array:

$file_name = $_FILES['file_var_name']['name'];

Then we can split the string with a _ delimiter like this:

$file_name_pieces = split('_', $file_name);

Then we'll have to iterate over the list and make a new string where all except the first spot have uppercase letters:

$new_file_name = '';
$count = 1;

foreach($file_name_pieces as $piece)
{
    if ($count !== 1)
    {
        $piece = ucfirst($piece);
    }

    $new_file_name .= $piece;
    $count++;
}

Now that we have the new filename, we can revisit what we did above. Basically, you do everything the same except you add this $config param:

$config['file_name'] = $new_file_name;

And that should do it! By default, CI has the overwrite $config param set to FALSE, so if there are any conflicts, it will append a number to the end of your filename. For the full list of parameters, see the link at the top of this post.

查看更多
▲ chillily
3楼-- · 2020-02-10 05:28
$this->load->helper('inflector');
$file_name = underscore($_FILES['file_var_name']['name']);
$config['file_name'] = $file_name;

that should work too

查看更多
我想做一个坏孩纸
4楼-- · 2020-02-10 05:36
$file_name = preg_replace('/[^a-zA-Z]/', '', ucwords($_FILES['file_var_name']['name']));
查看更多
登录 后发表回答