Codeigniter替换已上传的图像

6
我正在使用Codeigniter的文件上传类上传用户头像。是否有一种方法可以在用户上传新头像时替换用户的图像文件?我想用最新上传的头像替换现有的头像。
我的图像上传控制器
function upload_avatar()
    {
        $config['upload_path'] = './uploads/avatars/';
        $config['allowed_types'] = 'jpg|png';
        $config['overwrite'] = FALSE; //overwrite user avatar
        $config['encrypt_name'] = TRUE;
        $config['max_size'] = '200'; //in KB

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload())
        {
            $error = $this->upload->display_errors(); 

            $this->session->set_flashdata('error', $error);

            redirect('/settings/avatar');
        }
        else
        {                
            $config['image_library'] = 'gd2';
            $config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
            $config['create_thumb'] = FALSE;
            $config['maintain_ratio'] = FALSE;
            $config['width'] = 120;
            $config['height'] = 120;

            $this->load->library('image_lib', $config); 

            $this->image_lib->crop();

            //Add image path to database
            $avatar_path = 'uploads/avatars/' . $this->upload->file_name;
            $user_id = $this->tank_auth->get_user_id();
            $this->Settings_model->update_avatar($avatar_path, $user_id);

            $this->session->set_flashdata('success', 'Avatar updated!');

            redirect('/settings/avatar');
        }
    }

2
你尝试将这行代码 $config['overwrite'] = FALSE; //overwrite user avatar 改为 TRUE 了吗? - drfranks3
3个回答

10

有一个名为overwrite的公共属性,它决定是否覆盖原始文件。默认情况下,将基于原始文件创建一个新的文件名。以下是CI中Upload.php的源代码:

/*
 * Validate the file name
 * This function appends an number onto the end of
 * the file if one with the same name already exists.
 * If it returns false there was a problem.
 */
$this->orig_name = $this->file_name;

if ($this->overwrite == FALSE)
{
    $this->file_name = $this->set_filename($this->upload_path, $this->file_name);

    if ($this->file_name === FALSE)
    {
        return FALSE;
    }
}

要使覆盖工作,你需要做的就是:

$this->load->library('upload', $config);
$this->upload->overwrite = true;

谢谢!为了让替换起作用,我想我需要给每个头像图像一个唯一的名称,比如用户的用户名。这样,用户上传的任何内容都会替换掉已经存储的内容。 - CyberJunkie

5
在你的配置文件中将简单设置"override"为true。
$this->upload->initialize(array(
            "upload_path"=>$path,
            "allowed_types"=>"jpg|png|jpeg",
            "overwrite"=>true
        ));

3

你试过更改吗?

$config['overwrite'] = FALSE;

to

$config['overwrite'] = TRUE;

1
$this->upload->overwrite = true;相比,一个不错的替代方案。 - Wouter Vanherck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接