codeigniter多个图像上传

时间:2017-07-21 21:49:31

标签: php image codeigniter image-uploading

我正在尝试上传多个图片以下代码,但它不起作用任何帮助将不胜感激下面是我的模型,控制器和视图。我正在使用codeigniter 3,我尝试使用下面的代码,但我没有得到我想要的结果。

控制器

 public function create(){
    //checking if user is logged in
    if(!$this->session->userdata('logged_in')){
        redirect('users/login');
    }
    $data['title'] = 'Create Post';

    // to populate categories from dropdown we fetch from database
    $data['categories'] = $this->post_model->get_categories();

    $this->form_validation-> set_rules('title', 'Title', 'required');
    $this->form_validation-> set_rules('body', 'Body', 'required');

    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|png|jpg|JPNG';
        $config['max_size'] = '2048';
        $config['max_width'] = '1500';
        $config['max_height'] = '1500';          
        $this->load->library('upload',$config);

        if(!$this->upload->do_upload()){
            $error = array('error' => $this->upload->display_errors());
            $post_image = 'noimage.jpg';
        }else{
            $data = array('upload_data' => $this->upload->data());

        $files = $_FILES;
          $post_image = count($_FILES['userfile']['name']);
          for($i=0; $i<$post_image; $i++)
            {
            $_FILES['userfile']['name']= time().$files['userfile']['name'][$i];
            $_FILES['userfile']['type']= $files['userfile']['type'][$i];
            $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
            $_FILES['userfile']['error']= $files['userfile']['error'][$i];
            $_FILES['userfile']['size']= $files['userfile']['size'][$i];
            $this->upload->initialize($config);
            $this->upload->do_upload();
            $fileName = $_FILES['userfile']['name'];
            $images[] = $fileName;
            }
              $fileName = implode(',',$images);
        }
        $this->post_model->create_post($post_image);

        // Set message to be sent
    $this->session->set_flashdata('post_created', 'Post Created');
        redirect('posts');
    }

}

模型

  public function create_post($post_image){
      $slug = url_title($this->input->post('title'));

      $data = array(
          'title' => $this->input->post('title'),
          'slug' => $slug,
          'body' => $this->input->post('body'),
          'category_id' => $this->input->post('category_id'),
          //the user
          'user_id' => $this->session->userdata('user_id'),
          'post_image' => $post_image
      );
    //posts is the table name  
      return $this->db->insert('posts', $data);
  }

查看

   <input name="userfile[]" type="file" multiple>

0 个答案:

没有答案