php - Codeigniter 替换上传的图片

标签 php codeigniter upload avatar

我正在使用 Codeigniter 的 File Uploading Class用于上传用户头像。有没有办法在他/她上传新图像文件时替换用户的图像文件?我想用上传的最新头像替换现有头像。

我的图片上传 Controller

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');
        }
    }

最佳答案

有一个公共(public)属性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;

关于php - Codeigniter 替换上传的图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11371882/

相关文章:

php - 在 mysql 中运行更新查询后返回更新后的值

javascript - Codeigniter:以管理员用户身份登录并以员工用户身份登录

regex - CodeIgniter 中的路由 : Matching specific length segment

ruby-on-rails - 发布请求不处理上传

google-app-engine - 在Google Cloud Storage签名的URL中提供回调URL

php - 内爆在不同的帖子中不起作用

php - POST 请求中的字符编码错误

php - Typo3介绍包版本9.5

php - 代码点火器 2 : How to extend CI_Controller multiple times?

c# - 如何在新的子窗口中实现文件上传?