Codeigniter 3 : how to get image file in callback

2019-09-06 03:29发布

i'm using codeigniter 3, i try to get image file from callback function, but i don't know how to write the code.

here my code in view and controller function

view

<?php echo validation_errors('<p class="form_error">','</p>'); ?>
<?php echo form_open_multipart('welcome/register/'); ?>
<input type="text" name="firstname" placeholder="Enter your Firstname"/>
<input type="text" name="city" placeholder="Enter your City"/>
<input type="file" name="userimage">
<button type="submit">Create Account</button>
</form>

controller function

public function register(){
 $this->load->library('form_validation');
 $this->form_validation->set_rules('firstname', 'First Name', 'required|trim|xss_clean');
 $this->form_validation->set_rules('city', 'City', 'required|trim|xss_clean');
 $this->form_validation->set_rules('userimage', 'Profile Image', 'callback_image_upload'); 
 if($this->form_validation->run() == TRUE){

     echo "image file in here - how to get image file from validation callback_image_upload ?";

 }
 $this->load->view('register'); 
} 

function image_upload(){
  if($_FILES['userimage']['size'] != 0){
    $upload_dir = './images/';
    if (!is_dir($upload_dir)) {
         mkdir($upload_dir);
    }   
    $config['upload_path']   = $upload_dir;
    $config['allowed_types'] = 'gif|jpg|png|jpeg';
    $config['file_name']     = 'userimage_'.substr(md5(rand()),0,7);
    $config['overwrite']     = false;
    $config['max_size']  = '5120';

    $this->load->library('upload', $config);
    if (!$this->upload->do_upload('userimage')){
        $this->form_validation->set_message('image_upload', $this->upload->display_errors());
        return false;
    }   
    else{
        $this->upload_data['file'] =  $this->upload->data();
        return true;
    }   
}   
else{
    $this->form_validation->set_message('image_upload', "No file selected");
    return false;
} 

question : how to get image file in function register() ?

2条回答
Viruses.
2楼-- · 2019-09-06 04:04

After the validation routine runs you can access the upload library in the register function. The method $this->loader->data() will supply you with everything you need to retrieve the image.

查看更多
Animai°情兽
3楼-- · 2019-09-06 04:11

that solve with :

$CI =& get_instance();
$upload_data = $CI->upload->data();
$image_file_name = $upload_data['file_name'];

After the validation routine runs i access the upload library in the register function with get_instance. and this work perfectly. thanks dude . @DFriend

查看更多
登录 后发表回答