Как загрузить файлы в codeigniter

1

Я использую рамки codeigniter для моего проекта, я загружаю изображения, поэтому я использую какой-то код. другие данные были вставлены, но изображение не было вставлено, я добавил свой код ниже. Спасибо заранее

Html:

<form method="post" enctype="multipart/form-data" action="<?php echo base_url(); ?>charity/insertCharity">
<div class="control-group" style="padding:15px;">
    <label class="control-label" for="basicinput" style="padding:10px;">Logo:</label>
<div class="controls">
    <div class="input-append span6">
        <input type="file" class="span12" placeholder="Upload file" name="logo">
    </div>
</div>
</div>

контроллер:

public function insertCharity(){
    $result = $this->charity_model->addCharity();
    if($result > 0){
        $data['mess'] = "Charity added successfully";
        $this->load->view('charity_view', $data);
    }
}

Модель:

public function addCharity(){
    $cha_name = $this->input->post('charity_name');
    $regno = $this->input->post('reg_no');
    $contact_per = $this->input->post('contact_person');
    $contact_no = $this->input->post('contact_no');
    $address = $this->input->post('address');
    $aboutCharity = $this->input->post('about_charity');
    $createdOn = date('Y-m-d H:i:s');
    if($_FILES['logo']['size'] != 0 )
    {

        $files = $_FILES;
        $config = array();
        $config['upload_path']   =   "charity_gallery/";
        $config['allowed_types'] =   "png|jpg|gif"; 
        $config['max_size']      =   "5000";
        $this->load->library('upload',$config);
        $this->upload->initialize($config);


        $this->upload->do_upload('logo');
        $imgdata = $this->upload->data();
        $image_config=array();          
        $image_config["image_library"] = "gd2";
        $image_config['overwrite'] = TRUE;
        $image_config["source_image"] = $imgdata["full_path"];
        $image_config['create_thumb'] = FALSE;
        $image_config['maintain_ratio'] = TRUE;
        $image_config['new_image'] = $imgdata["file_path"].$imgdata["file_name"];
        $image_config['quality'] = "95%";
        $image_config['width'] = 170;
        $image_config['height'] = 170;
        $this->load->library('image_lib',$image_config);
        $this->image_lib->initialize($image_config);    
        $this->image_lib->resize();
        $logo = 'charity_gallery/'.$imgdata["file_name"];




        $query = $this->db->query("INSERT INTO 'charities' (charity_name, reg_no, contact_person, contact_number, address, about, logo, created_on) VALUES ('$cha_name', '$regno', '$contact_per', '$contact_no', '$address', '$aboutCharity', '$logo', '$createdOn')");
        //$cid = $this->db->insert_id();
        $aff = $this->db->affected_rows();
        return $aff;
    }else{
        $query = $this->db->query("INSERT INTO 'charities' (charity_name, reg_no, contact_person, contact_number, address, about, created_on) VALUES ('$cha_name', '$regno', '$contact_per', '$contact_no', '$address', '$aboutCharity', '$createdOn')");
        //$cid = $this->db->insert_id();
        $aff = $this->db->affected_rows();
        return $aff;
    }


}

Все значение вставлено, но только логотип не получает вставленное имя папки, вставленное как "charity_gallery". Я не знаю, где я иду не так, пожалуйста, направляйте меня

Теги:
codeigniter

2 ответа

0
Лучший ответ

На самом деле я использовал машину ubuntu, поэтому я забыл дать разрешение на папку с изображениями. После того, как я дал разрешение, я получил ответ

2

Попробуйте с изменением name атрибута входного файла в userfile. Существует примечание в документации

Примечание. По умолчанию программа загрузки ожидает, что файл будет получен из поля формы с именем userfile


Также попробуйте отладить с помощью (это приведет к выгрузке ошибок при загрузке, если они есть):

if ( ! $this->upload->do_upload())
{
    echo $this->upload->display_errors();
    exit();
}
  • 0
    Привет, спасибо за ваш ответ. На самом деле я пропустил $ this-> load-> helper (array ('form', 'url')); в моем коде. моя проблема была решена, когда я добавил это ... спасибо за ваши ответы, брат
  • 0
    Хорошо. Не добавляйте их отдельно в каждый контроллер. Добавьте их один раз в файл autoload.php расположенный в каталоге application/config .
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню