файл загрузки codeigniter не загружен

#php #codeigniter

#php #codeigniter

Вопрос:

 $config['upload_path'] = './assets/images/gambar_paket/';
            $config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; 
            $config['max_size'] = 1000;
            $config['max_width'] = 1024; 
            $config['max_height'] = 900;
            $config['file_name'] = $file;
            $this->load->library('upload', $config);
            $this->upload->do_upload();

            $data = array('nama_paket' => $nama,
                          'deskripsi' => $deskripsi,
                          'harga' => $harga,
                          'jenis' => $jenis,
                          'gambar' => $file
                         );
            $this->mod_main->createData($data,'paket');
            redirect('con_main/packet','refresh');
  

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

Ответ №1:

             $config['upload_path'] = './assets/images/gambar_paket/';
            $config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; 
            $config['max_size'] = 1000;
            $config['max_width'] = 1024; 
            $config['max_height'] = 900;
            $config['file_name'] = $file;
            $this->load->library('upload', $config);
            $this->upload->do_upload();
            if(!$this->upload->do_upload()){
                $error = array('error' => $this->upload->display_errors());
                echo <div class="alert alert-danger">'.$error['error'].'</div>';
            }else{
               $data = array('nama_paket' => $nama,
                          'deskripsi' => $deskripsi,
                          'harga' => $harga,
                          'jenis' => $jenis,
                          'gambar' => $file
               );
            $this->mod_main->createData($data,'paket');
            redirect('con_main/packet','refresh');
}
  

1: -Используйте сообщение об ошибке, оно покажет вам ошибку

2: -Также проверьте, имеет ли ваша форма enctype=’multipart/form-data’

3: -проверьте имя файла и используйте userfile -> необязательно

4: -перед отправкой данных выведите $ _FILES[‘файл пользователя’], чтобы проверить, отсутствуют ли ваши данные в uplaod

5: -Также проверьте загружаемый загрузочный файл.Или загрузить вручную

Ответ №2:

Ошибка, из-за которой ваш файл не загружается по указанному пути, заключается в том, что вы указали относительный путь для каталога загрузки

 $config['upload_path'] = './assets/images/gambar_paket/';
  

Следовательно, реальный путь должен быть заменен на FCPATH

Вот некоторые из кодов, которые необходимо использовать.

 EXT: The PHP file extension
FCPATH: Path to the front controller (this file) (root of CI)
SELF: The name of THIS file (index.php)
BASEPATH: Path to the system folder
APPPATH: The path to the "application" folder
  

Следовательно, вам нужно заменить две строки ниже в вашем коде загрузчика:

Заменить:

 $config['upload_path'] = './assets/images/gambar_paket/';
$this->upload->do_upload();
  

С:

 $config['upload_path'] = FCPATH ."assets/fileupload/";
$this->upload->do_upload('userimage'); // Where userimage is the name of the file uplaoder input type name
  

HTML будет выглядеть следующим образом:

 <input type="file" name="userimage"/>
  

И вся функция загрузки будет выглядеть следующим образом.

 $config['upload_path'] = FCPATH ."assets/images/gambar_paket/";
$config['allowed_types'] = 'gif|jpg|png';
$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; 
$config['max_size'] = 1000;
$config['max_width'] = 1024; 
$config['max_height'] = 900;
$config['file_name'] = $file;
$this->load->library('upload', $config);
$this->upload->initialize($config);     
if ( ! $this->upload->do_upload('userimage'))  {// Here you can handle the Failure Upload}
else
{ $data = $this->upload->data(// Here you can handle the operations after the image is uploaded);}
  

Вот пример формы, которая вам нужна для загрузки изображения из синтаксиса HTML:

 <?php
echo form_open_multipart('employee/addemployee', array('name' => 'addemployee', 'class'=>'form-horizontal'));
?>
<div class="form-group">
     <label class="control-label col-sm-4" for="pwd">Profile:</label>
     <div class="col-sm-8">
        <input type="file" class="" id="profile" name="userimage">
     </div>
</div>
<?php
echo form_close();
?>
  

Примечание: он перенаправит на employee/addemployee который Employee Controller вызывается функция поиска и поиска addemployee , и там у вас есть код для загрузки изображения, а затем сохранения его с использованием модели.

Я надеюсь, что это объяснение будет понятным, чтобы понять ошибку, которую вы получаете, и исправить ее в дальнейших проектах, которые вы делаете.

Счастливого кодирования 🙂

Ответ №3:

Пример модели

 public function InsertBerita(){
    // Direktori File "folder-CI->berita"
    $config['upload_path'] = './berita/';
    // Format Image
    $config['allowed_types'] = 'jpg|png|jpeg';
    $config['encrypt_name'] = TRUE;
    // Load Libary Uploud
    $this->load->library('upload', $config);
    if ($this->upload->do_upload()) {
        $cekUser = $this->db->get_where('berita', array('judul_berita' => $this->input->post('judul_berita')));
        unlink("berita/".$cekUser->first_row()->cover_berita);
        $data['upload_data'] = $this->upload->data();
        $this->resize($data['upload_data']['full_path'], $data['upload_data']['file_name']);
        $file_gambar = $data['upload_data']['file_name'];
        $insert = $this->db->insert('berita', array(
            'cover_berita' => $file_gambar,
            'ringkasan_berita' => $this->input->post('ringkasan_berita'),
            'judul_berita' => $this->input->post('judul_berita'),
            'isi_berita' => $this->input->post('isi_berita'),
            'tanggal_berita' => date('Y-m-d H:i:s'),
            'id_admin' => '1',
            ));
        sleep(2);
        redirect(base_url('databerita?insertsuccess'));

    }else{
        redirect(base_url('insertberita?failed'));
    }
}

// image manipulasi merisize
public function resize($path,$file){
    $config['image_library']='GD2';
    $config['source_image'] = $path;
    $config['maintain_ratio'] = TRUE;
    $config['create_thumb'] = FALSE;
    // size image
    $config['width'] = 1158;
    $config['height'] = 550;
    // kualitas diturunkan 20%
    $config['quality'] = 20;
    $config["image_sizes"]["square"] = array(1158, 550);
    $this->load->library('image_lib', $config);
    $this->image_lib->fit();
}
enter code here
  

Библиотека Гунакан вслух Джанган Лупа

Ответ №4:

 $config['upload_path'] = './assets/images/gambar_paket/';
            $config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; 
            $config['max_size'] = 1000;
            $config['max_width'] = 1024; 
            $config['max_height'] = 900;
            $this->load->library('upload', $config);
            $this->upload->do_upload();

            $data = array('nama_paket' => $nama,
                          'deskripsi' => $deskripsi,
                          'harga' => $harga,
                          'jenis' => $jenis,
                          'gambar' => $config['upload_path'] . $this->upload->data('file_name')
                         );
            $this->mod_main->createData($data,'paket');
            redirect('con_main/packet','refresh');
  

Semoga bisa membantu. Jangan lupa dibuat dahulu folder assets/images/gambar_paket