CodeIgniter图像文件无法上传

时间:2017-09-11 18:19:42

标签: php mysql codeigniter

我无法解决的一个问题,我尝试了所有可能的解决方案,但我不顺利 好吧,问题是当我想上传图片时,我从我的comp中选择图片,当我点击提交按钮时,图片没有上传,并且它显示了我放在用户不选择图像的情况下的defaule图像( noimage.jpg) 上传图像的功能从create()方法开始

帖子控制器

<?php


class Posts extends CI_Controller{

    public function __construct(){
        parent::__construct();
        $this->load->database();    
        $this->load->library('upload');

    }

    public function index($offset = 0){



        $config['base_url'] = base_url() . 'posts/index/';
        $config['total_rows'] = $this->db->count_all('posts');
        $config['per_page'] = 3;
        $config['uri_segment'] = 3;
        $config['attributes'] = array('class' => 'pagination-link');

        $this->pagination->initialize($config);

        $data['posts']= $this->Posts_model->get_posts(FALSE,$config['per_page'],$offset);

        $this->load->view('templates/header');
        $this->load->view('posts/index',$data);
        $this->load->view('templates/footer');



    }


    public function view($mjestoOdredista=NULL){


        $data['posts'] = $this->Posts_model->get_posts($mjestoOdredista);
        $post_id = $data['posts']['id'];
        $data['comments'] = $this->comment_model->get_comments($post_id);

        if(empty($data['posts'])){
            show_404();
        }
        $data['id'] =$data['posts'];

        $this->load->view('templates/header');
        $this->load->view('posts/view',$data);
        $this->load->view('templates/footer');


    }


    public function create(){
        //check if user is logged in
        if(!$this->session->userdata('logged_in')){
            redirect('users/login');
        }

       $this->form_validation->set_rules('mjestoPolaska', 'Mjesto Polaska', 'required');
       $this->form_validation->set_rules('mjestoOdredista', 'Mjesto Odredista', 'required');
       $this->form_validation->set_rules('datumPolaska', 'Datum Polaska', 'required');
       $this->form_validation->set_rules('datumPovratka', 'Datum Povratka', 'required');
       $this->form_validation->set_rules('cijena', 'Cijena', 'required');
       $this->form_validation->set_rules('brojMjesta', 'Broj mjesta', 'required');
       $this->form_validation->set_rules('opis', 'Opis', 'required');


        $data['title'] ='Create Posts';
        $data['categories'] = $this->Posts_model->get_categories();

        if($this->form_validation->run()===FALSE){

            $this->load->view('templates/header');
            $this->load->view('posts/create',$data);
            $this->load->view('templates/footer');

        }else {

            //upload image
            $config['upload_path'] = './assets/images/posts';
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size'] = '2048';
            $config['max_width'] = '100';
            $config['max_height'] = '100';

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


            if(!$this->upload->do_upload('userfile')){
                $errors = array('error'=>$this->upload->display_errors());
                $post_image='noimage.jpg';
            }else{
                $data = array('upload_data'=>$this->upload->data());
                $post_image = $_FILES['userfile']['name'];
            }
            $this->Posts_model->create_post($post_image);
            $this->session->set_flashdata('post_creted', 'You post has been created') ;
            redirect('posts');
        }

    }

    public function delete($id){

        if(!$this->session->userdata('logged_in')){
            redirect('users/login');
        }


        $this->Posts_model->delete_post($id);
        $this->session->set_flashdata('post_deleted', 'You post has been deleted  ') ;
        redirect('posts');
    }



    public function edit($mjestoOdredista){
        if(!$this->session->userdata('logged_in')){
            redirect('users/login');
        }

        $data['posts']= $this->Posts_model->get_posts($mjestoOdredista);

        //Check if user is logged in
        if($this->session->userdata('user_id') != $this->Posts_model->get_posts($mjestoOdredista)['user_id']){
            redirect('posts');
        }

        $data['categories'] = $this->Posts_model->get_categories();

        if(empty($data['posts'])){
            show_404();
        }

        $data['title'] = 'Edit Post';
        $this->load->view('templates/header');
        $this->load->view('posts/edit',$data);
        $this->load->view('templates/footer');
    }


    public function update(){
        if(!$this->session->userdata('logged_in')){
            redirect('users/login');
        }

        $this->Posts_model->update_post();
        $this->session->set_flashdata('post_updated', 'You post has been updated ') ;
        redirect('posts');

    }

    }

?>

Posts_model

<?php


class Posts_Model extends CI_Model{

    public function __construct(){
        $this->load->database();

    }

    function get_posts($mjestoOdredista=FALSE, $limit = FALSE,$offset = FALSE){
        if($limit){
            $this->db->limit($limit,$offset);
        }
        if($mjestoOdredista === FALSE){

            $this->db->order_by('posts.id','DESC');
            $this->db->join('categories','categories.id = posts.category_id');
            $query=$this->db->get('posts');
            return $query->result_array();
        }

        $query=$this->db->get_where('posts', array('mjestoOdredista' => $mjestoOdredista));


        return $query->row_array();
    }

    //Kreiranje post
    public function create_post($post_image){
        $mjestoPolaska = url_title($this->input->post('title'));
        $data=array(
                'mjestoPolaska' => $this->input->post('mjestoPolaska'),
                'mjestoOdredista' => $this->input ->post('mjestoOdredista'),
                'datumPolaska' => $this->input ->post('datumPolaska'),
                'datumPovratka' => $this->input ->post('datumPovratka'),
                'brojMjesta' => $this->input ->post('brojMjesta'),
                'cijena' => $this->input ->post('cijena'),
                'opis' => $this->input ->post('opis'),
                'category_id'=>$this->input->post('category_id'),
                'user_id' =>$this->session->userdata('user_id'),
                'post_image'=>$post_image

        );

        return $this->db->insert('posts',$data);
    }

    //Brisanje posta
    public function delete_post($id){
        $this->db->where('id',$id);
        $this->db->delete('posts');
        return true;
    }


    //editovanje posta
    public function update_post(){
        $mjestoOdredista = url_title($this->input->post('title'));
        $data=array(
                'category_id' => $this->input->post('category_id'),
                'mjestoPolaska' =>   $this->input->post('mjestoPolaska'),
                'mjestoOdredista' => $this->input->post('mjestoOdredista'),
                'datumPolaska' =>    $this->input ->post('datumPolaska'),
                'datumPovratka' =>   $this->input ->post('datumPovratka'),
                'cijena' =>          $this->input ->post('cijena'),
                'brojMjesta' =>      $this->input ->post('brojMjesta'),
                'opis' =>            $this->input ->post('opis'),

        );
        $this->db->where('id', $this->input->post('id'));
        return $this->db->update('posts', $data);

    }

    public function get_categories(){
        $this->db->order_by('name');
        $query = $this->db->get('categories');
        return $query->result_array();
    }

    public function get_posts_by_category($category_id){

        $this->db->order_by('posts.id','DESC');

        $this->db->join('categories','categories.id = posts.category_id');
        $query=$this->db->get_where('posts',array('category_id'=>   $category_id));
        return $query->result_array();

    }



}



?>

创建视图

<h2><?= $title;?></h2>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<script>
  $( function() {
        $("#datepicker").datepicker({
            dateFormat: 'dd-mm-yy'
        });
        $("#datepicker1").datepicker({
            dateFormat: 'dd-mm-yy'
        }); 
  });
  </script>


<?php echo form_open_multipart('posts/create/');?>
<?php echo validation_errors();?>

    <div class="row">
        <div class="col-md-4 col-md-offset-4">

                <div class="form-group">
                    <label>Mjesto Polaska</label>
                    <input type="text" class="form-control" name="mjestoPolaska" placeholder="Mjesto Polaska">
                </div>


                <div class="form-group">
                    <label>Mjesto Odredista</label>
                    <input type="text" class="form-control" name="mjestoOdredista" placeholder="Mjesto Odredista">
                </div>

                <div class="form-group">
                    <label>Datum Polaska</label>
                     <input type="date" id="datepicker" class="form-control" name="datumPolaska" placeholder ="Datum Polaska" >
                </div>

                <div class="form-group">
                    <label>Datum Povratka</label>
                     <input type="date" id="datepicker1" class="form-control" name="datumPovratka" placeholder="Datum Povratka">
                </div>



                <div class="form-group">
                <label>Cijena</label>
                <input type="text" class="form-control" name="cijena" placeholder="Cijena">
                </div>

                <div class="form-group">
              <label for="select">Broj slobodnih mjesta</label>
                  <select class="form-control" id="select" name="brojMjesta">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                  </select>
                </div>


            <div class="form-group">
            <label for="kategorije">Kategorija</label>
             <?php 
             echo '<select class="form-control" id="kategorije" name="category_id">';
             foreach($categories as $category) :
                echo '<option value="' . $category['id'] . '">' . $category["name"] . '</option>';
             endforeach;
             echo '</select>';
             ?>
            </div>

            <div class="form-group">
             <label>Postavi sliku:</label>
             <p><b>samo oni koji nude prevoz nek postave sliku svojeg vozila</b></p>
             <input type="file" name="userfile" size="20">
             </div>

             <div class="form-group">
              <label>Opis:</label>
              <textarea class="form-control" rows="5" id="comment" name="opis"></textarea>
            </div>
                <button type="submit" class="btn btn-primary btn-block">Submit</button>

            </div>
    </div>

2 个答案:

答案 0 :(得分:2)

试试这个

用此代码替换create函数

    public function create()
    {
    //check if user is logged in
    if (!$this->session->userdata('logged_in')) {
    redirect('users/login');
    }

    $this->form_validation->set_rules('mjestoPolaska', 'Mjesto Polaska', 'required');
    $this->form_validation->set_rules('mjestoOdredista', 'Mjesto Odredista', 'required');
    $this->form_validation->set_rules('datumPolaska', 'Datum Polaska', 'required');
    $this->form_validation->set_rules('datumPovratka', 'Datum Povratka', 'required');
    $this->form_validation->set_rules('cijena', 'Cijena', 'required');
    $this->form_validation->set_rules('brojMjesta', 'Broj mjesta', 'required');
    $this->form_validation->set_rules('opis', 'Opis', 'required');


    $data['title'] = 'Create Posts';
    $data['categories'] = $this->Posts_model->get_categories();

    if ($this->form_validation->run() === FALSE) {

      $this->session->set_flashdata("error", validation_errors());
      $this->load->view('templates/header');
      $this->load->view('posts/create', $data);
      $this->load->view('templates/footer');
    } else {

      if (empty($_FILES['userfile']['name'])) {
        $this->session->set_flashdata('error', "Please select image");
        redirect(site_url() . 'posts/create');
      }

      $path = 'assets/images/posts/';
      $post_image = $this->ImageUpload($path, 'userfile', '');
      if (!is_array($post_image)) {

        $this->session->set_flashdata('error', $post_image);
        redirect(site_url() . 'posts/create');
      }
      $post_image = $post_image['file_name'];

      $this->Posts_model->create_post($post_image);
      $this->session->set_flashdata('post_creted', 'You post has been created');
      redirect('posts');
    }
  }

  public function ImageUpload($upload_path, $uploading_file_name, $file_name = '') {

    $obj = &get_instance();
    $obj->load->library('upload');
    //echo $uploading_file_name.$file_name;
    $file_name = 'image_' . time() . $file_name . "." . pathinfo($_FILES[$uploading_file_name]['name'], PATHINFO_EXTENSION);
    $full_path = FCPATH . $upload_path;
    //       $full_path = $upload_path;// uncomment if you using windows os
    // if folder is not exists then create the folder
    //if (!is_dir($full_path)) {
    // mkdir($full_path, 0775);
    //}

    $config['upload_path'] = $full_path;
    $config['allowed_types'] = 'gif|jpg|png|jpeg|GIF|JPG|PNG|JPEG';
    $config['max_size'] = 2048;
    $config['max_width'] = 2048;
    $config['max_height'] = 2048;
    $config['file_name'] = $file_name;

    $obj->upload->initialize($config);

    if (!$obj->upload->do_upload($uploading_file_name)) {
      return $obj->upload->display_errors();
    } else {
      return $obj->upload->data();
    }
  }

<?php echo validation_errors();?>替换为<?php echo $this->session->flashdata("error")?>

或者您可以使用布局库而不是调用header n footer [https://code.tutsplus.com/tutorials/how-to-create-a-layout-manager-with-codeigniter--net-15533]

  

FCPATH仅适用于linux系统,如果出现错误FCPATH,请检查path is wrong

答案 1 :(得分:2)

如果存储没有图像的数据则

def get_dataframe_for_product_id(your_input_df, wanted_product_id):
    df2 = your_input_df.groupby(['user_id'])
    result = pd.DataFrame([],columns=your_input_df.columns)
    for key, val in df2:
        result = pd.concat([result, val[val.order_id > val[val.product_id == wanted_product_id].order_id.max()]])
    return result