“文件上传失败:上传路径在 CodeIgniter 3 中似乎无效”

问题描述 投票:0回答:1

我正在 CodeIgniter 3 中开发文件上传功能,但遇到以下错误:

文件上传失败:上传路径似乎无效。

问题详情如下:

上传文件夹可写(应用chmod 777),并且目录路径正确。 我想将上传的图像保存在数据库中并在视图中显示。 这是我的控制器代码:

public function add_details()
{
    $config['upload_path'] = FCPATH . 'uploads/';
    $config['upload_path'] = './upload/';
    $config['allowed_types'] = 'jpg|png|jpeg';
    $config['max_size'] = 2048;

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

    if (!$this->upload->do_upload('image')) {
        $error = $this->upload->display_errors();
        log_message('error', 'File upload failed: ' . $error);
        $this->session->set_flashdata('error', 'File upload failed: ' . $error);
    } else {
        $imageData = $this->upload->data();
        $record = [
            'title' => $this->input->post('title'),
            'description' => $this->input->post('description'),
            'image' => base_url('uploads/' . $imageData['file_name']),

        ];


        if ($this->DashboardModel->add_details($record)) {
            $this->session->set_flashdata('success', 'Details added successfully.');
        } else {
            $this->session->set_flashdata('error', 'Failed to save details to the database.');
        }
    }

    redirect(base_url('dashboard'));
}

}

我想上传图片,将其路径保存到数据库中,并在视图中显示上传的图片。

codeigniter-3
1个回答
0
投票

改进你的代码

public function add_details()
{
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'jpg|png|jpeg';
    $config['max_size'] = 2048;

    // Load upload library with the configuration
    $this->load->library('upload', $config);

    // Handle file upload
    if (!$this->upload->do_upload('image')) {
        // Log and flash error message
        $error = $this->upload->display_errors();
        log_message('error', 'File upload failed: ' . $error);
        $this->session->set_flashdata('error', 'File upload failed: ' . $error);
    } else {
        // Retrieve uploaded image data
        $imageData = $this->upload->data();

        // Prepare data for saving to the database
        $record = [
            'title' => $this->input->post('title'),
            'description' => $this->input->post('description'),
            'image' => 'uploads/' . $imageData['file_name'], // Store relative path in the database
        ];

        // Save to the database
        if ($this->DashboardModel->add_details($record)) {
            $this->session->set_flashdata('success', 'Details added successfully.');
        } else {
            $this->session->set_flashdata('error', 'Failed to save details to the database.');
        }
    }

    // Redirect to dashboard
    redirect(base_url('dashboard'));
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.