CodeIgniter图像上传功能

时间:2014-03-23 18:18:28

标签: php codeigniter

当我尝试保存其他数据时,如何上传图片?当表单提交时,它会点击保存功能:

function save() {
   $this->save_data($_POST, $_FILES);
}    

function save_data($post_data, $file_data) {
    // if theres an image
    if(!empty($file_data['image']['size'])) {
        $path = '/images';
        $this->upload_image($path);
    }
}

function upload_image($path) {
    // CI is looking for $_FILES super global but I want to pass that data in
    $config['upload_path'] = $path;
    $config['allowed_types'] = 'jpg|png';
    $config['max_size'] = '100';
    $config['max_width']  = '1024';
    $config['max_height']  = '768';
    $this->load->library('upload', $config);
    $this->upload->data('image');
    $this->upload->do_upload('image');
}

我无法弄清楚如何将文件数据实际传递给另一个函数。我见过的所有示例都显示了提交给函数的表单,该函数从中上传函数。我想从其他功能上传。

2 个答案:

答案 0 :(得分:1)

如果您正在尝试检查文件是否实际上传,请执行以下操作

//this is optional
if (empty($_FILES['userfile']['name'])) {

    $this->form_validation->set_rules('userfile', 'picture', 'required');

}

if ($this->form_validation->run()) { //if using validation
    //validated
    if (!empty($_FILES['userfile']['name'])) {
        //picture is beeing uploaded

        $config['upload_path'] = './files/pcitures';
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['encrypt_name'] = TRUE;

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

        if (!$this->upload->do_upload('userfile')) {

            //$error = array('error' => $this->upload->display_errors());

        } else {

            //no error, insert/update in DB
            $tmp = $this->upload->data();
            echo "<pre>";
            var_dump($tmp);
            echo "</pre>";
        }

    } else { ... }

}

答案 1 :(得分:1)

我的错误与文件夹权限有关。

对于那些希望将上传功能拆分为多个功能的人:

<强>控制器:

$save_data = $this->save_model->save_data($_POST, $_FILES);

<强>型号:

function save_data($data, $file) {
    // check if theres an image
    if (!empty($file['image']['size'])) {
        // where are you storing it
        $path = './images';
        // what are you naming it
        $new_name = 'name_' . random_string('alnum', 16);
        // start upload
        $result = $this->upload_image($path, $new_name);
    }
}

function upload_image($path, $new_name) {
    // define parameters
    $config['upload_path'] = $path;
    $config['allowed_types'] = 'jpg|png';
    $config['max_size'] = '1000';
    $config['max_width'] = '1024';
    $config['max_height'] = '768';
    $config['file_name'] = $new_name;
    $this->load->library('upload', $config);
    // upload the image
    if ($this->upload->do_upload('image')) {
        // success
        // pass back $this->upload->data() for info
    } else {
        // failed
        // pass back $this->upload->display_errors() for info
    }
}