Using CodeIgniter, I am trying to modify 开发者_Python百科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
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.
$this->load->helper('inflector');
$file_name = underscore($_FILES['file_var_name']['name']);
$config['file_name'] = $file_name;
that should work too
$file_name = preg_replace('/[^a-zA-Z]/', '', ucwords($_FILES['file_var_name']['name']));
精彩评论