动态编码器图像上传重命名


Dynamically Codeigniter Image Upload Rename

我正在用以下代码上传多个带有codeigniter的动态图像。

foreach ($_FILES as $key => $value) {   
    $imagePrefix = time();                                  
    if (!$this->upload->do_upload($key))
    {
        echo $errors = $this->upload->display_errors();
        return '';
    }
    else
    {
        $imagename = $imagePrefix.$value['name'];
        $insertImage = $this->db->query("Insert into `tbl_event_imges` (`iEventID`,`vImage`) values ('".$insertId."','".$imagename."')");
    }
}

当我上传一个图像到特定的文件夹这工作良好;问题是,如果用户上传具有相同名称的图像,那么它将自动重命名图像并上传到文件夹,但我想要的是通过添加我在else部分代码中添加的$imagePrefix来重命名它,然后想要上传具有此名称的图像。但这对我不起作用。

有什么建议吗?

您需要为上传函数提供配置首选项,如下所示:

$imagePrefix = time(); 
$imagename = $imagePrefix.$value['name'];
$this->load->library('upload');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = $imagename; // set the name here
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)){
    ...
}else{
    ...
}

来源:http://www.codeigniter.com/user_guide/libraries/file_uploading.html?highlight=file%20upload setting-preferences

作为备选,您可以使用CI的重命名功能在文件上传后重命名。

$image = $this->upload->data();
$file_path = $image ['file_path'];
$file = $image ['full_path'];
$file_ext = $image['file_ext'];
$final_file_name = time() . $image['file_name'] . $file_ext;

仅添加以下代码即可运行成功,并将encrypt_name设置为false

$path = $_FILES['userfile']['name'];
$newName = "Add any name".".".pathinfo($path, PATHINFO_EXTENSION);
$config['file_name'] = $newName; 
$config['encrypt_name'] = false;