繁体   English   中英

CodeIgniter图片上传功能

[英]CodeIgniter Image Upload Function

尝试与图像一起保存其他数据时如何上传图像? 提交表单后,将点击保存功能:

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

我不知道如何实际将文件数据传递给另一个函数。 我所看到的所有示例都显示了表单提交给函数的过程,该函数直接从中上载函数。 我想从其他功能上传。

如果您要检查文件是否真正上传,请执行以下操作

//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 { ... }

}

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

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

控制器:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM