Upload Image or File in codeigniter

In Codeigniter we have to design code to frontend and the backend in frontend we have to design html form with input type file.

and in backend we have to give upload file.

Add the following files in application/views/files

  • upload_form.php – this view contains the HTML form that has the input type of file and submits the selected file to the server for processing
  • upload_result.php – this view displays the results of the uploaded image including a link that we can click to view the results.

Add the following code to upload_form.php




    CodeIgniter Image Upload
    
    


    

Select an image from your computer and upload it to the cloud

HERE,

  • if (isset($error)){…} checks if the error variable has been set. If the result is true then the error returned by the upload library is displayed to the user.
  • the type file allows the user to browser to their computer and select a file for uploading.

Ad the following code to upload_result.php




    Image Upload Results
    
    


    

Congratulations, the image has successfully been uploaded

Click here to view the image you just uploaded

Now We have to create function in Controller

Add the following code to upload_form.php

function volunteer_register() {
        $config1['upload_path'] = 'profiles/';
        $config1['allowed_types'] = 'jpg|jpeg|png|gif';
        $config1['encrypt_name']         = TRUE;
        $config['max_size'] = '1000000';
        $config['max_width']  = '1024000';
        $config['max_height']  = '768000';
        $config1['file_name'] = $_FILES['userfile1']['name'];
        $this->load->library('upload',$config1);
        $this->upload->initialize($config1);
        if($this->upload->do_upload('userfile1')){
            //echo 'haii'; exit;
            $uploadData1 = $this->upload->data();
            $picture = $uploadData1['file_name'];
        }else{
            //echo 'bye'; exit;
            $picture = '';
         }
	 $userType = $this->input->post('userType');
          
            $new_member_insert_data1 = array(
                'vImage' => $picture
                );
           $affectedRows = $this->Home_model->insert("volunteer", $new_member_insert_data1);
            if ($affectedRows == 1) {
                    $this->session->set_flashdata('successmsg', 'Your image uploaded');
                    redirect('home/image');
                } else {
                    $this->session->set_flashdata('errormsg', 'Sorry, Some Errors Occured, please try Later');
                    redirect('home/image');
                }
             }