【问题标题】:Codeigniter 3 : how to get image file in callback validation function?Codeigniter 3:如何在回调验证函数中获取图像文件?
【发布时间】:2016-08-25 11:06:59
【问题描述】:

我正在使用codeigniter 3,我尝试从回调函数中获取图像文件,但我不知道如何编写代码。

这是我在视图和控制器功能中的代码

查看

<?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>

控制器功能

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;
} 

问题: 如何在函数 register() 中获取图像文件?

【问题讨论】:

    标签: codeigniter callback


    【解决方案1】:

    验证例程运行后,您可以访问注册函数中的upload 库。 $this-&gt;loader-&gt;data() 方法将为您提供检索图像所需的一切。

    【讨论】:

      【解决方案2】:

      解决方法:

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

      验证例程运行后,我使用 get_instance 访问注册函数中的上传库。这完美地工作。多谢,伙计 。 @DFriend

      【讨论】:

      • 不客气。您可以简单地使用$this-&gt;upload-&gt;data('file_name')。我犯了一个错误,不包括$this-&gt;(我已经添加了)
      猜你喜欢
      • 1970-01-01
      • 2015-07-04
      • 2015-06-27
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      • 2022-08-05
      相关资源
      最近更新 更多